linux下消息队列小例子

/*
编写消息队列时需要注意 

1. msgbuf_debug_t 自定义结构体中data成员的大小设置,若过大则会报无效参数之类的错误。

    客户端与服务端最好该结构体大小一致,且发送端的数据不能超过接收端buf大小。

2. msgbuf_debug_t 结构体中type值在两端最好设置一致。*/ //客户端: #include <unistd.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/stat.h> #include <signal.h> typedef struct msgbuf_debug { long type; char data[5120]; }msgbuf_debug_t; int msgid = -1; static void sig_handle(int sig) { msgctl(msgid, IPC_RMID, 0); printf("SIGINT exit\n"); exit(0); } int main(int argc, char** argv) { key_t key; int i; if (argc == 1) { printf("help info:\n"); printf("shu ru ge shi: ./a.out taskid\n"); return 0; } int taskid = atoi(argv[1]); taskid += 100; printf("argv[1]:%s :%d\n", argv[1], taskid); signal(SIGINT, sig_handle); msgbuf_debug_t msg; /*key*/ key=ftok("/dev/null", taskid); if(key==-1) printf("ftok err:%m\n"),exit(-1); /*create msg_queue*/ msgid=msgget(key,IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR | 0666); if(msgid==-1)printf("get err:%m\n"),exit(-1); /*recv*/ while(1) { memset(&msg,0, sizeof(msg)); msg.type=2; if (msgrcv(msgid,&msg,sizeof(msg.data),2,0) == -1) { printf("msgrcv error: %s\n", strerror(errno)); return -1; } printf("%s\n",msg.data); } return 0; }

//服务端部分代码:

	taskid += 100;
	msg.type = 2;
	key_t key = ftok("/dev/null", taskid);
	if (key == -1)
	{
		printf("ftok error: %s", strerror(errno));
		return;
	}
	
	S32 msgid = msgget(key, S_IRUSR | S_IWUSR);
	printf("msgid  %d, taskid: %d", msgid, taskid);
	if (msgid == -1)
	{	

		printf("msgget error: %s", strerror(errno));
		return;
	}

	/*...*/
	/*...*/

	/*IPC_NOWAIT*/   

	if (msgsnd(msgid, msg, sizeof(msg->data), 0) == -1) 

	{

		printf("msgsnd error: %s", strerror(errno)); 

		return;

	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值