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;
}
相关推荐
早起鸟儿39 分钟前
docker-Dockerfile 配置
java·linux·运维·docker
love530love4 小时前
是否需要预先安装 CUDA Toolkit?——按使用场景分级推荐及进阶说明
linux·运维·前端·人工智能·windows·后端·nlp
m0_694845574 小时前
日本云服务器租用多少钱合适
linux·运维·服务器·安全·云计算
一心0924 小时前
Linux部署bmc TrueSight 监控agent步骤
linux·运维·服务器·监控·bmc truesight
Florence234 小时前
linux中执行脚本命令的source和“.”和“./”的区别
linux·运维·服务器
白日依山尽yy4 小时前
Linux02
linux·运维·服务器
liulilittle5 小时前
通过高级处理器硬件指令集AES-NI实现AES-256-CFB算法并通过OPENSSL加密验证算法正确性。
linux·服务器·c++·算法·安全·加密·openssl
flypig哗啦啦6 小时前
ubuntu桌面x11异常修复
linux·运维·ubuntu
will_net6 小时前
Linux入门(十六)shell&shell变量&设置环境变量&位置参数变量&预定义变量
linux·运维·chrome
LetsonH6 小时前
Ubuntu 实现 sudo 免密码关键步骤
linux·运维·ubuntu