两个进程间的通信

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

#define MSGKEY   1234

struct msgbuf {
	long mtype;     /* message type, must be > 0 */
	char mtext[64];  /* message data */
};

int main()
{
	struct msgbuf mbuf;
	int ret;

	int msgid = msgget(MSGKEY, IPC_CREAT | IPC_EXCL);
	if (-1 == msgid)
	{
		perror("msgget");
		exit(1);
	}

	pid_t pid = fork();
	if (-1 == pid)
	{
		perror("fork");
		exit(1);
	}
	else if (0 == pid)    //子进程发送
	{
		while (1)
		{
			memset(&mbuf, 0, sizeof(mbuf));
	
			mbuf.mtype = 1;   //消息类型
			scanf("%s", mbuf.mtext);

			ret = msgsnd(msgid, &mbuf, sizeof(mbuf.mtext), 0);
			if (-1 == ret)
			{
				perror("msgsnd");
				exit(1);
			}

			if (!strcmp(mbuf.mtext, "bye"))
			{
				mbuf.mtype = 2;
				msgsnd(msgid, &mbuf, sizeof(mbuf.mtext), 0);
				break;
			}
		}
	}
	else                 //父进程接收
	{
		while (1)
		{
			memset(&mbuf, 0, sizeof(mbuf));
		
			ret = msgrcv(msgid, &mbuf, sizeof(mbuf.mtext), 2, 0);
			if (-1 == ret)
			{
				perror("msgrcv");
				exit(1);
			}

			if (!strcmp(mbuf.mtext, "bye"))
			{	
				kill(pid, 2);
				break;
			}
			
			printf("\t\t\t%s\n", mbuf.mtext);

			memset(&mbuf, 0, sizeof(mbuf));
		}
	}

	sleep(1);
	msgctl(msgid, IPC_RMID, NULL);

	return 0;
}

 

 

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

#define MSGKEY   1234

struct msgbuf {
	long mtype;     /* message type, must be > 0 */
	char mtext[64];  /* message data */
};

int main()
{
	struct msgbuf mbuf;
	int ret;

	int msgid = msgget(MSGKEY, 0);
	if (-1 == msgid)
	{
		perror("msgget");
		exit(1);
	}

	pid_t pid = fork();
	if (-1 == pid)
	{
		perror("fork");
		exit(1);
	}
	else if (0 == pid)    //子进程发送
	{
		while (1)
		{
			memset(&mbuf, 0, sizeof(mbuf));
	
			mbuf.mtype = 2;   //消息类型
			scanf("%s", mbuf.mtext);

			ret = msgsnd(msgid, &mbuf, sizeof(mbuf.mtext), 0);
			if (-1 == ret)
			{
				perror("msgsnd");
				exit(1);
			}

			if (!strcmp(mbuf.mtext, "bye"))
			{
				mbuf.mtype = 1;
				msgsnd(msgid, &mbuf, sizeof(mbuf.mtext), 0);
				break;
			}
		}
	}
	else                 //父进程接收
	{
		while (1)
		{
			memset(&mbuf, 0, sizeof(mbuf));
		
			ret = msgrcv(msgid, &mbuf, sizeof(mbuf.mtext), 1, 0);
			if (-1 == ret)
			{
				perror("msgrcv");
				exit(1);
			}

			if (!strcmp(mbuf.mtext, "bye"))
			{
				kill(pid, 2);
				break;
			}
			
			printf("\t\t\t%s\n", mbuf.mtext);

			memset(&mbuf, 0, sizeof(mbuf));
		}
	}

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值