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;
}
相关推荐
2501_907136821 小时前
离线工具箱 内含53个小工具
linux·服务器·网络
时空潮汐2 小时前
神卓N600 NAS身份核验功能深度解析
linux·运维·网络·神卓nas·神卓n600 pro·家庭轻nas
哈哈浩丶2 小时前
安卓系统全流程启动
android·linux·驱动开发
小李独爱秋2 小时前
模拟面试:用自己的话解释一下lvs的工作原理
linux·运维·面试·职场和发展·操作系统·lvs
一路往蓝-Anbo2 小时前
第 7 章:内存地图 (Memory Map) 深度设计——DDR 与 SRAM
linux·stm32·单片机·嵌入式硬件·网络协议
BHXDML2 小时前
VMware Workstation Pro 安装详细教程(超详细图文讲解)
linux·虚拟机
一路往蓝-Anbo3 小时前
第 8 章:M33 领航——引导 A35 加载 U-Boot 与 Linux 内核
linux·运维·服务器·stm32·单片机·嵌入式硬件·网络协议
一路往蓝-Anbo4 小时前
第 6 章:GPIO 与外部中断——M33 掌控下的 LED 与按键响应
linux·stm32·单片机·嵌入式硬件
闲人编程5 小时前
任务监控与错误重试
linux·服务器·网络·celery·任务队列·任务监控·错误重试
REDcker7 小时前
FTP协议原理及应用精解
linux·后端·计算机网络·互联网·ftp·服务端开发