消息队列服务器客户端测试

//server.c
#include <stdio.h>  
#include <string.h>  
#include <stdlib.h>  
#include <errno.h>  
#include <unistd.h>  
#include <sys/types.h>  
#include <sys/ipc.h>  
#include <sys/stat.h>  
#include <sys/msg.h>
 
#define FILE_MSG "dm14_消息队列serverTest.c"

struct msgbuff
{
	long mtype;
	char buffer[1024];
};

int main()
{
	key_t key;
	int msgid;
	int rcvbytes = 0;
	struct msgbuff msg_rcvbuf;
	key = ftok(FILE_MSG, '20');
	if(key == -1)
	{
		printf("ftok error!  \n");
		return -1;
	}
	
	msgid = msgget(key,S_IRUSR|S_IWUSR|IPC_CREAT|IPC_EXCL);
	if(msgid == -1)
	{
		printf("msgget error!  \n");
		return -1;
	}
	
    while(1)
	{
		rcvbytes = msgrcv(msgid, &msg_rcvbuf, sizeof(struct msgbuff), 1, 0);
		if(rcvbytes == -1)
		{
			printf("msgrcv error! \n");
			return -1;
		}

		printf("recv %d bytes msg from client : %s \n", rcvbytes, msg_rcvbuf.buffer);
	
	}
	
	return 0;
}
//client
#include <stdio.h>  
#include <string.h>  
#include <stdlib.h>  
#include <errno.h>  
#include <unistd.h>  
#include <sys/types.h>  
#include <sys/ipc.h>  
#include <sys/stat.h>  
#include <sys/msg.h>
 
#define FILE_MSG "dm14_消息队列serverTest.c"

struct msgbuff
{
	long mtype;
	char buffer[1024];
};

int main()
{
	struct msgbuff msg_sndbuf;
	key_t key;
	int msgid;
	int sndbytes = 0;
	key = ftok(FILE_MSG, '20');
	if(key == -1)
	{
		printf("ftok error!\n");
		return -1;
	}
	
	msgid = msgget(key, S_IRUSR|S_IWUSR);
	if(msgid == -1)
	{
		printf("msgget error!\n");
		return -1;
	}
	
    msg_sndbuf.mtype = 1;
	strcpy(msg_sndbuf.buffer,"helloworld");
	sndbytes = msgsnd(msgid, &msg_sndbuf, sizeof(struct msgbuff), 0);
	if(sndbytes == -1)
	{
		printf("msgsnd error!\n");
		return -1;
	}
	
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值