歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux服務器 >> Linux關於消息隊列的使用

Linux關於消息隊列的使用

日期:2017/3/2 16:33:22   编辑: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 © Linux教程網 All Rights Reserved