5月13号作业

使用消息队列实现的2个终端之间的互相聊天 并使用信号控制消息队列的读取方式: 当键盘按ctrl+c的时候,切换消息读取方式,一般情况为读取指定编号的消息,按ctrl+c之后,指定的编号不读取,读取其他所有编号的消息

cpp 复制代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
int brr=0;
struct msgbuf
{
	long mtype;
	char mtext[128];
};
void *run(void *arg)
{  
	int* mytype=(int*)arg;
  	key_t key=ftok("./ipc",1);
  	if(key==-1)
  	{
      	perror("ftok");
      	return NULL;
  	}
  	int id=msgget(key,IPC_CREAT|0666);
  	if(id==-1)
  	{
      	perror("msgget");
      	return NULL;
  	}
  	struct msgbuf msg;
  	int size=0;
  	while(1)                                      
  	{
		if(brr==0)
		{
      		memset(&msg,0,sizeof(msg));
      		msgrcv(id,&msg,128,*mytype,IPC_NOWAIT);
			if(strlen(msg.mtext)!=0)
			{
				putchar(10);
      			printf("读取到的消息为:%s\n",msg.mtext);
				printf("请输入:");
				fflush(stdout);
			}
			else
			{
				;
			}
		}
		else if(brr==1)
		{
      		memset(&msg,0,sizeof(msg));
      		msgrcv(id,&msg,128,*mytype,IPC_NOWAIT|020000);
			if(strlen(msg.mtext)!=0)
			{
      			putchar(10);
      			printf("读取到的消息为:%s\n",msg.mtext);
      			printf("请输入:");
      			fflush(stdout);
			}
			else
			{
				;
			}
		}
  	}
}
void handler(int signum)
{
	if(signum==SIGINT)
	{
		brr=(brr+1)%2;
		printf("%d\n",brr);
	}
	
}
int main(int argc, const char *argv[])
{
	pthread_t id1;
	int mytype1=atoi(argv[2]);
	pthread_create(&id1,0,run,&mytype1);
	int mytype=atoi(argv[1]);
	key_t key=ftok("./ipc",1);
	if(key==-1)
	{
		perror("ftok");
		return 1;
	}
	int id=msgget(key,IPC_CREAT|0666);
	if(id==-1)
	{
		perror("msgget");
		return 1;
	}
	struct msgbuf msg;
	int size=0;
	signal(SIGINT,handler);
	while(1)
	{
		memset(&msg,0,sizeof(msg));
		msg.mtype=mytype;
		printf("请输入:");
		scanf("%128s",msg.mtext);
		while(getchar()!='\n');
		size=strlen(msg.mtext);
		msgsnd(id,&msg,size,0);
 
	}
	return 0;
}
相关推荐
wzhao1015 分钟前
elf_loader:一个使用Rust编写的ELF加载器
linux·rust·gnu
lllsure8 小时前
Linux 实用指令
linux·物联网
努力的小T9 小时前
使用 Docker 部署 Apache Spark 集群教程
linux·运维·服务器·docker·容器·spark·云计算
Nerd Nirvana9 小时前
OpenSSL crt & key (生成一套用于TLS双向认证的证书密钥)
linux·ssl·shell·认证·加密·tls·oepnssl
letisgo510 小时前
记录一次部署PC端网址全过程
linux·阿里云·服务器运维
猫猫的小茶馆10 小时前
【网络编程】UDP协议
linux·服务器·网络·网络协议·ubuntu·udp
尚墨111110 小时前
linux 安装启动zookeeper全过程及遇到的坑
linux·zookeeper
鱼嘻10 小时前
Linux自学day23-进程和线程
linux·服务器·c语言·进程和线程
AuGuSt_8110 小时前
在windows下安装windows+Ubuntu16.04双系统(下)
linux·ubuntu·双系统
old_power11 小时前
Linux(Ubuntu24.04)源码编译安装OpenCV4.6.0
linux·opencv