实验十 Linux消息传递通信

写消息:

#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<stdio.h>
#include<stdlib.h>

typedef struct _msg_buf
{
	long type;//消息类型
	char buf[100];//消息类型
}msg_buf;

int main()
{
	int key,qid;
	int wc=1;
	msg_buf buf;
	key=ftok(".",10);
	qid=msgget(key,IPC_CREAT|0666);
	printf("key:%d\nqid=%d\n",key,qid);
	buf.type=10;
	system("ipcs -q");//查看当前存在的消息队列
	printf("请输入一些消息,每条消息以回车结束,如果输入quit,则程序结束\n");
	while(1)
	{
		//循环输入消息到队列
		system("ipcs -q");
		printf("输入第%d条消息:",wc++);
		fgets(buf.buf,100,stdin);
		if(strncmp(buf.buf,"quit",4)==0)
		{
			if((msgctl(qid,IPC_RMID,NULL))<0)//删除指定的消息队列
			{
				perror("msgctl");
				exit(1);
			}
			else
			{
				printf("successfully removed %d queue\n",qid);
				exit(0);
			}
		}
		if(msgsnd(qid,(void*)&buf,100,0)<0)
		{
			perror("msgsnd");
			exit(-1);
		}
	}

	return 0;
}

读消息:

#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<stdio.h>
#include<stdlib.h>

typedef struct _msg_buf
{
	long type;
	char buf[100];
} msg_buf;

int main()
{
	int key,qid;
	msg_buf buf;
	key=ftok(".",10);
	qid=msgget(key,IPC_CREAT|0666);
	while(1)
	{
		if(msgrcv(qid,(void*)&buf,100,0,0)<0)
		{
			perror("msgrcv");
			exit(-1);
		}

		system("ipcs -q");
		printf("type:%ld\nget:%s\n",buf.type,buf.buf);
	}

	return 0;
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值