读书人

linux 讯息序列(进程间通信)

发布时间: 2012-09-17 12:06:51 作者: rapoo

linux 消息序列(进程间通信)

#include <stdlib.h>#include <stdio.h>#include <string.h>#include <errno.h>#include <unistd.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>//需要自己定义的消息队列结构struct msgStuct{  long int msgType;  char strMsg[1024];};intmain (){  int msgid;  struct msgStuct msg_data;  //接收消息优先级  long int msgPriority = 0;//从队列中取第一个  //创建一个消息队列  if ((msgid= msgget ((key_t) 2234, 0666 | IPC_CREAT)) == -1)//类似open()创建一个文件返回它的文件描述符,这里是消息序列    {      perror ("msgget failed with error");      exit (EXIT_FAILURE);    }  while (1)    {//接收消息      if (msgrcv (msgid, (void *) &msg_data, 1024,  msgPriority, 0) == -1){  perror ("msgrcv failed with error");  exit (EXIT_FAILURE);}      printf ("Received message: %s", msg_data.strMsg);      if (strncmp (msg_data.strMsg, "end", 3) == 0){  break;}    }  //删除消息队列  if (msgctl (msgid, IPC_RMID, 0) == -1)    {      fprintf (stderr, "delete messagequeue error\n");      exit (EXIT_FAILURE);    }  exit (EXIT_SUCCESS);}

第一个是send.c,第二个是recieve.c

读书人网 >UNIXLINUX

热点推荐