消息队列发
struct msgbuf{ long mtype; char mtext[128]; }; int main() { struct msgbuf readbuf; int msgid = msgget(0x1235,IPC_CREAT|0777);//创建消息队列 if(msgid == -1){ printf("get que failuer\n");//如果返回值为-1,说明创建失败 } msgrcv(msgid,&readbuf,sizeof(readbuf.mtext),888,0);//读取消息 printf("read from que:%s\n",readbuf.mtext);//打印输出 struct msgbuf sendbuf = {988,"thank you for reach"};//创建消息结构体 msgsnd(msgid,&sendbuf,strlen(sendbuf.mtext),0);//添加消息,发送上面的sendbuf的内容 return 0; }
消息队列收
#include<stdio.h> #include<sys/types.h> #include<sys/ipc.h> #include<string.h> #include<sys/msg.h> struct msgbuf{ long mtype; char mtext[128]; }; int main() { struct msgbuf sendbuf = {888,"this is message from quen"}; struct msgbuf readbuf; int msgid = msgget(0x1235,IPC_CREAT|0777);//创建消息队列 if (msgid == -1){ printf("get que failuer\n"); } msgsnd(msgid,&sendbuf,strlen(sendbuf.mtext),0);//添加消息 printf("send over\n"); msgrcv(msgid,&readbuf,sizeof(readbuf.mtext),988,0);//读取消息 printf("reaturn from get %s\n",readbuf.mtext);//打印输出读取的消息 return 0; } ~
运行显示