Linux关于消息队列的使用


今天完成消息队列的使用。

  消息队列类似FIFO,但是可以实现随机查询。

  主要函数:msgget,msgsnd,msgrcv,msgctl

  实验实现两个进程之间的通信。

  一个发送,一个接受。并不需要额外实现进程同步。

  源代码来自华清远见:

  发送:

  #include<sys/types.h>

  #include<sys/ipc.h>

  #include<sys/msg.h>

  #include<stdio.h>

  #include<stdlib.h>

  #include<unistd.h>

  #include<string.h>

  #define BUFFER_SIZE 512

  struct message

  {

  long msg_type;

  char msg_text[BUFFER_SIZE];

  };

  int main()

  {

  int qid;

  key_t key;

  struct message msg;

  //ftok根据不同路径和关键字产生标准的KEY

  if((key = ftok(".", 'a')) == -1)

  {

  perror("ftok");

  exit(1);

  }

  if((qid = msgget(key, IPC_CREAT|0666)) == -1)//创建

  {

  perror("msgget");

  exit(1);

  }

  printf("open queue %d\n", qid);

  while(1)

  {

  printf("enter some message to the queue:");

  if((fgets(msg.msg_text, BUFFER_SIZE, stdin)) == NULL)

  {

  puts("no message");

  exit(1);

  }

  msg.msg_type = getpid();//消息类型为进程号

  if((msgsnd(qid, &msg, strlen(msg.msg_text), 0)) < 0)//发送消息

  {

  perror("message posted");

  exit(1);

  }

  if(strncmp(msg.msg_text, "quit", 4) == 0)

  {

  break;

  }

  }

  exit(0);

  }

  接收:

  #include<sys/types.h>

  #include<sys/ipc.h>

  #include<sys/msg.h>

  #include<stdio.h>

  #include<stdlib.h>

  #include<unistd.h>

  #include<string.h>

  #define BUFFER_SIZE 512

  struct message

  {

  long msg_type;

  char msg_text[BUFFER_SIZE];

  };

  int main()

  {

  int qid;

  key_t key;

  struct message msg;

  if((key = ftok(".", 'a')) == -1)

  {

  perror("ftok");

  exit(1);

  }

  if((qid = msgget(key, IPC_CREAT|0666)) == -1)//创建

  {

  perror("msgget");

  exit(1);

  }

  printf("open queue %d\n", qid);

  do

  {

  memset(msg.msg_text, 0, BUFFER_SIZE);

  if(msgrcv(qid, (void*)&msg, BUFFER_SIZE, 0, 0) < 0)//接收消息

  {

  perror("msgrcv");

  exit(1);

  }

  printf("the message from process %d : %s", msg.msg_type, msg.msg_text);

  }while(strncmp(msg.msg_text, "quit", 4));

  if((msgctl(qid, IPC_RMID, NULL)) < 0)//从系统内核移走消息队列

  {

  perror("msgctl");

  exit(1);

  }

  exit(0);

  }

  打开两个终端,1号发送,2号接收


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3