1. 程式人生 > >使用訊息佇列實現兩程序間實時通訊的例子

使用訊息佇列實現兩程序間實時通訊的例子

int main()
{
 int msgid;
 unsigned char running=1;
 char buff[MAX_TEXT];
 MSG_REC  recivemsg;
 printf("receive msg process is starting!\n");
 printf("the process id=%d\n",getpid());
 msgid=msgget((key_t)12345,0777|IPC_CREAT);
 if(msgid==-1)
 {
  perror("msgget");
  exit(1);
 }
 while(running)
 {
  memset(&recivemsg,0,sizeof(MSG_REC));
  //printf("please int msg:");
  //fgets(buff,MAX_TEXT,stdin);
  //recivemsg.my_msg_type =1;
  //strcpy(recivemsg.msg_text,buff);
  if(msgrcv(msgid,(void *)&recivemsg,MAX_TEXT,0,0)==-1)
  {
   perror("msgsnd");
   exit(1);
  }
  printf("the receive msg :%s",recivemsg.msg_text);
  
  if(strncmp(recivemsg.msg_text,"end",3)==0)
  {
   printf("the program will exit\n");
   running=0;
  }
 }
 return 0;
}