第五章Linux消息队列

华清实验教材的demo简单易懂

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


#define N 64


#define TypeA 100
#define TypeB 200


#define LEN (sizeof(MSG) - sizeof(long))


typedef struct
{
	long mtype;
	char mtext[N];
} MSG;


int main()
{
	key_t key;
	int msgid;
	MSG buf;
	pid_t pid;


	if ((key = ftok(".", 'm')) < 0)//使用ftok生成唯一的key
	{
		perror("fail to ftok");
		exit(-1);
	}


	if ((msgid = msgget(key, 0666|IPC_CREAT)) < 0)//请求消息队列
	{
		perror("fail to msgget");
		exit(-1);
	}


	if ((pid = fork()) < 0)
	{
		perror("fail to fork");
		exit(-1);
	}
	else if (pid == 0)  // recv message
	{
		while ( 1 )
		{
			msgrcv(msgid, &buf, LEN, TypeA, 0);
			if (strncmp(buf.mtext, "quit", 4) == 0) 
			{
				kill(getppid(), SIGUSR1);
				msgctl(msgid, IPC_RMID, NULL);
				exit(0);
			}
			printf("recv from clientB : %s\n", buf.mtext);
		}
	}
	else  // send message
	{
		buf.mtype = TypeB;
		while ( 1 )
		{
			printf("send to clientB : ");
			fgets(buf.mtext, N, stdin);
			msgsnd(msgid, &buf, LEN, 0);
			if (strncmp(buf.mtext, "quit", 4) == 0) 
			{
				kill(pid, SIGUSR1);
				exit(0);
			}
		}
	}


	return 0;
}


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

#define N 64

#define TypeA 100
#define TypeB 200

#define LEN (sizeof(MSG) - sizeof(long))

typedef struct
{
	long mtype;
	char mtext[N];
} MSG;

int main()
{
	key_t key;
	int msgid;
	MSG buf;
	pid_t pid;

	if ((key = ftok(".", 'm')) < 0)
	{
		perror("fail to ftok");
		exit(-1);
	}

	if ((msgid = msgget(key, 0666|IPC_CREAT)) < 0)
	{
		perror("fail to msgget");
		exit(-1);
	}

	if ((pid = fork()) < 0)
	{
		perror("fail to fork");
		exit(-1);
	}
	else if (pid == 0)  // recv message
	{
		while ( 1 )
		{
			msgrcv(msgid, &buf, LEN, TypeA, 0);
			if (strncmp(buf.mtext, "quit", 4) == 0) 
			{
				kill(getppid(), SIGUSR1);
				msgctl(msgid, IPC_RMID, NULL);
				exit(0);
			}
			printf("recv from clientB : %s\n", buf.mtext);
		}
	}
	else  // send message
	{
		buf.mtype = TypeB;
		while ( 1 )
		{
			printf("send to clientB : ");
			fgets(buf.mtext, N, stdin);
			msgsnd(msgid, &buf, LEN, 0);
			if (strncmp(buf.mtext, "quit", 4) == 0) 
			{
				kill(pid, SIGUSR1);
				exit(0);
			}
		}
	}

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值