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;
}
相关推荐
byte轻骑兵2 分钟前
异构混合环境远程控制工具适配对比(Windows / Mac / Linux / 国产系统 / arm64 / 鸿蒙)
linux·windows·macos·远程办公
jiecy35 分钟前
用 AI 手搓海康视频播放插件:NVR 在 Linux 网页下实时播放、回放
linux·运维·服务器
第404号工位2 小时前
从 USB MSC 写入缓存与 exFAT/NTFS 日志机理看“安全弹出”的本质:Linux dirty page 与 FTL 实测
linux·操作系统
海边捡石子2 小时前
用 Nuitka 保护 Python 核心业务源码
linux·后端·python
YMWM_2 小时前
ubuntu24.04自带录屏软件使用指南
linux·具身智能
qetfw3 小时前
Debian 磁盘实验:RAID5、LVM 与 LUKS 分层及挂载验证
linux·运维·debian·raid
沫璃染墨4 小时前
从零入门计算机网络系列(三十三):Linux I/O 多路复用详解——epoll 核心接口、底层原理与事件通知机制
linux·运维·服务器·c++·驱动开发·系统架构·硬件架构
Rabitebla4 小时前
【Linux】文件系统(四):目录、路径解析与 dentry 缓存
linux·数据结构·c++·笔记·学习·算法·缓存
爆米花byh4 小时前
在RockyLinux9环境下安装RustFS Server1.0.6单机版
linux·中间件
光电的一只菜鸡4 小时前
ubuntu之坑(二十二)——看门狗
linux·单片机·ubuntu