首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

基于消息队列的进程间通讯的有关问题

2012-11-04 
基于消息队列的进程间通讯的问题C/C++ code#include stdio.h#include sys/types.h#include sys/shm.h

基于消息队列的进程间通讯的问题

C/C++ code
#include <stdio.h>#include <sys/types.h>#include <sys/shm.h>#include <sys/msg.h>#include <sys/ipc.h>#include <unistd.h>int qid;int open_q(int key){        if((qid=msgget(key,IPC_CREAT|0777))==-1)                {                return -1;                }                return (qid);}int main(){        key_t key=75;        int i;        struct msgbuf{        long mtype;             //结构体函数;        char mtext[1];        struct msgbuf *next;        }mbuf;        pid_t server,client;        struct msgbuf *p;       //指向结构体的指针;        open_q(key);            //创建一个队列;        p = &mbuf;        if((client=fork())==0)        {                for(i=10;i>0;i--)                {                mbuf.mtype = i;                msgsnd(qid,p,1024,IPC_NOWAIT);                sleep(1);                printf("(Client) sent\n");                                                       }        else        {                if((server=fork())==0)                {                while(mbuf.mtype!=1)                        {                        msgrcv(qid,p,1024,mbuf.mtype,0);                        printf("(Server) receive");                        }                msgctl(qid,IPC_RMID,NULL);                }        }        return 0;}


用的是linux 的gcc,用fork函数创建了两个子进程,一个作为server端,一个作为client端,client的发送类型从10到1,同时server端接收,当接收到类型为1的时候结束接收并取消队列。我写完发现,只能看到(Client) sent ,但是看不到(Server) receive,我觉得是server子进程没有建立成功,但也不是很确定,请各位帮忙分析一下

[解决办法]
送信 和 收信的size 对吗
sizeof(struct msgbuf) - sizeof(long)
[解决办法]
少了个 } 号吧
[解决办法]
C/C++ code
if((server=fork())==0)                {                while(mbuf.mtype!=1)                        {                        msgrcv(qid,p,1024,mbuf.mtype,0);                        printf("(Server) receive");                        }                msgctl(qid,IPC_RMID,NULL);                } 

热点排行