转自:http://blog.csdn.net/lifan5/article/details/7588529
/*send.c*/ #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <errno.h> #define MSGKEY 1024 struct msgstru { long msgtype; char msgtext[2048]; }; main() { struct msgstru msgs; int msg_type; char str[256]; int ret_value; int msqid; msqid=msgget(MSGKEY,IPC_EXCL); /*检查消息队列是否存在*/ if(msqid < 0){ msqid = msgget(MSGKEY,IPC_CREAT|0666);/*创建消息队列*/ if(msqid <0){ printf("failed to create msq | errno=%d [%s] ",errno,strerror(errno)); exit(-1); } } int c; while (1){ printf("input message type(end:0):"); scanf("%d",&msg_type); //while ( (c=getchar()) != ' ' && c != EOF ) {;} getchar(); //fflush(stdin); //C和C++的标准里从来没有定义过 fflush(stdin) if (msg_type == 0) break; printf("input medssage to be sent:"); //scanf ("%s",str); fgets(str,1024,stdin); msgs.msgtype = msg_type; strcpy(msgs.msgtext, str); /* 发送消息队列 */ ret_value = msgsnd(msqid,&msgs,sizeof(struct msgstru),IPC_NOWAIT); if ( ret_value < 0 ) { printf("msgsnd() write msg failed,errno=%d[%s] ",errno,strerror(errno)); exit(-1); } } msgctl(msqid,IPC_RMID,0); //删除消息队列 }
/*receive.c */ #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <errno.h> #define MSGKEY 1024 struct msgstru { long msgtype; char msgtext[2048]; }; /*子进程,监听消息队列*/ void childproc(){ struct msgstru msgs; int msgid,ret_value; char str[512]; while(1){ msgid = msgget(MSGKEY,IPC_EXCL );/*检查消息队列是否存在 */ if(msgid < 0){ printf("msq not existed! errno=%d [%s] ",errno,strerror(errno)); sleep(2); continue; } /*接收消息队列*/ ret_value = msgrcv(msgid,&msgs,sizeof(struct msgstru),0,0); printf("text=[%s] pid=[%d] ",msgs.msgtext,getpid()); } return; } void main() { int i,cpid; /* create 5 child process */ for (i=0;i<5;i++){ cpid = fork(); if (cpid < 0) printf("fork failed "); else if (cpid ==0) /*child process*/ childproc(); } }