基于消息队列的进程间通讯的问题
#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;}
if((server=fork())==0) { while(mbuf.mtype!=1) { msgrcv(qid,p,1024,mbuf.mtype,0); printf("(Server) receive"); } msgctl(qid,IPC_RMID,NULL); }