IO day7

使用消息队列实现两个进程间的相互通信

代码:

1.c

#include <head.h>

struct msgbuf
{
	long mtype;
	char mtext[1024];
	char ntext[1024];
};

#define SIZE sizeof(struct msgbuf)-sizeof(long)

int main(int argc, const char *argv[])
{
	pid_t pid = fork();
	if( pid < 0)
	{
		perror("fork");
		return -1;
	}

	key_t key = ftok("./",'k');
	if(key == -1)
	{
		perror("ftok");
		return -1;
	}

	int msgid = msgget(key, IPC_CREAT |0664);
	if(msgid == -1)
	{
		perror("msgget");
		return -1;
	}


	struct msgbuf info = {.mtype = 100};
	

	if(pid > 0)
	{
		struct msgbuf info = {.mtype = 50};
		while(1)
		{
			bzero(info.ntext,sizeof(info.ntext));

			msgrcv(msgid,&info,SIZE,50,0);

			printf("消息为%s\n",info.ntext);
			if(strcmp(info.ntext,"\0") == 0)
			{
				break;
			}
		}

	}


	else if(pid == 0)
	{
		while(1)
		{
			bzero(info.mtext,sizeof(info.mtext));

			//		printf("请输入:");
			fgets(info.mtext,SIZE,stdin);
			info.mtext[strlen(info.mtext)-1] = 0;

			msgsnd(msgid,&info,SIZE,0);

			if(strcmp(info.mtext,"quit") == 0)
			{
				break;
			}
		}
		if(msgctl(msgid,IPC_RMID,NULL) == -1)
		{
			perror("msgctl");
			return -1;
		}
		exit(0);
	}
	wait(NULL);

	return 0;
}

2.c

#include <head.h>

struct msgbuf
{
	long mtype;
	char mtext[1024];
	char ntext[1024];
};

#define SIZE sizeof(struct msgbuf)-sizeof(long)

int main(int argc, const char *argv[])
{
	pid_t pid = fork();
	if( pid < 0 )
	{
		perror("fork");
		return -1;
	}

	key_t key = ftok("./",'k');
	if(key == -1)
	{
		perror("ftok");
		return -1;
	}

	int msgid = msgget(key, IPC_CREAT |0664);
	if(msgid == -1)
	{
		perror("msgget");
		return -1;
	}



	if(pid > 0)
	{
		struct msgbuf info = {.mtype = 100};
		while(1)
		{
			bzero(info.mtext,sizeof(info.mtext));

			msgrcv(msgid,&info,SIZE,100,0);

			printf("消息为%s\n",info.mtext);
			if(strcmp(info.mtext,"\0") == 0)
			{
				break;
			}
		}
	}

	else if(pid == 0)
	{
		struct msgbuf info = {.mtype = 50};
		while(1)
		{
			bzero(info.ntext,sizeof(info.ntext));

		//	printf("请输入:");
			fgets(info.ntext,SIZE,stdin);
			info.ntext[strlen(info.ntext)-1] = 0;

			msgsnd(msgid,&info,SIZE,0);

			if(strcmp(info.ntext,"quit") == 0)
			{
				break;
			}
		}
		if(msgctl(msgid,IPC_RMID,NULL) == -1)
		{
			perror("msgctl");
			return -1;
		}

		exit(0);

	}
	wait(NULL);

	return 0;
}

运行结果:

思维导图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值