生活随笔
收集整理的這篇文章主要介紹了
消息队列的全双工通信
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
創建兩個進程,使每個都能讀寫消息隊列
代碼:
msg_service.c
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>struct msgbuf
{long mtype
;char mtest
[128];char ID
[4];
};int main()
{struct msgbuf sendbuf
,readbuf
;int msgid
;key_t key
;pid_t pid
;int readret
;key
=ftok("b.c",5);msgid
= msgget(key
,0755|IPC_CREAT
);if(msgid
== -1){printf("create message queue failed!\n");return -1;}system("ipcs -q");printf("create message queue success msgid =%d\n",msgid
);sendbuf
.mtype
=100;pid
=fork();if(pid
==-1){printf("fork fail\n");return -1;}if(pid
> 0){while(1){memset(sendbuf
.mtest
,0,128);printf("please input to massage queue:\n");fgets(sendbuf
.mtest
,128,stdin);msgsnd(msgid
,(void *)&sendbuf
,strlen(sendbuf
.mtest
),0);}}if(pid
== 0){while(1){memset(readbuf
.mtest
,0,128);readret
=msgrcv(msgid
,(void *)&readbuf
,128,99,0);printf("receive byte form message queue is :%s\n",readbuf
.mtest
);printf("total have %d byte\n",readret
);}}return 0;}
代碼:
msg_client.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>struct msgbuf
{long mtype
;char mtest
[128];char ID
[4];
};int main()
{struct msgbuf sendbuf
,readbuf
;int msgid
;key_t key
;pid_t pid
;int readret
;key
=ftok("b.c",5);msgid
= msgget(key
,0755|IPC_CREAT
);if(msgid
== -1){printf("create message queue failed!\n");return -1;}system("ipcs -q");printf("create message queue success msgid =%d\n",msgid
);sendbuf
.mtype
=99;pid
=fork();if(pid
==-1){printf("fork fail\n");return -1;}if(pid
== 0){while(1){printf("please input to massage queue:\n");fgets(sendbuf
.mtest
,128,stdin);msgsnd(msgid
,(void *)&sendbuf
,strlen(sendbuf
.mtest
),0);memset(sendbuf
.mtest
,0,128);}}if(pid
> 0){while(1){memset(readbuf
.mtest
,0,128);readret
=msgrcv(msgid
,(void *)&readbuf
,128,100,0);printf("receive byte form message queue is :%s\n",readbuf
.mtest
);printf("total have %d byte\n",readret
);}}return 0;}```執行結果:
&sendbuf
,strlen(sendbuf
.mtest
),0);中最后的參數
0表示,當消息返送完才返回,所以沒有消息發送時,進程會一直卡在這,
msgrcv(msgid
,(void *)&readbuf
,128,100,0);中最后一個參數
0表示,若無消息函數一直阻塞,所以沒有讀取到消息時,函數也會一直卡在這。
總結
以上是生活随笔為你收集整理的消息队列的全双工通信的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。