/*
编写消息队列时需要注意
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;
}