创建队列号:
#include <stdio.h>
#include <sys/msg.h>
#include <sys/ipc.h>
int main(int argc, char *argv[])
{
int id;
id = msgget(IPC_PRIVATE, IPC_CREAT|0660);
printf("id = %d\n", id);
return 0;
}
发送:
#include <stdio.h>
#include <string.h>
#include <sys/msg.h>
#include <sys/ipc.h>
typedef struct mymsg{
long msgtype;
char mdata[100];
}msg_t;
int main(int argc, char *argv[])
{
int ret;
int msgq_id;
char *msgstr;
msg_t msg;
if(argc < 3)
{
printf("please run this with msgqueue id and msgbody.\n");
return -1;
}
msgq_id = atoi(argv[1]);
if(msgq_id < 0)
{
printf("wrong queue id:%d.\n", msgq_id);
return -2;
}
printf("msgq_id:%d.\n", msgq_id);
msgstr = argv[2];
memset(&msg, 0, sizeof(msg));
msg.msgtype = 1;
strcpy(msg.mdata, msgstr);
ret = msgsnd(msgq_id, &msg, strlen(msg.mdata), IPC_NOWAIT);
printf("ret:%d.\n", ret);
return 0;
}
接收:
#include <stdio.h>
#include <string.h>
#include <sys/msg.h>
#include <sys/ipc.h>
typedef struct mymsg{
long msgtype;
char mdata[100];
}msg_t;
int main(int argc, char *argv[])
{
int s;
int msgq_id;
msg_t msg;
if(argc < 2)
{
printf("please run with msgqueue id.\n");
return -1;
}
msgq_id = atoi(argv[1]);
if(msgq_id < 0)
{
printf("wrong queue id:%d.\n", msgq_id);
return -2;
}
while(1)
{
memset(&msg, 0, sizeof(msg));
s = msgrcv(msgq_id, &msg, 100, 0, IPC_NOWAIT);
if(-1 != s)
printf("s:%d,msg.mdata:%s. msg.msgtype:%d\n", s, msg.mdata, msg.msgtype);
sleep(1);
}
return 0;
}