首页 | 源码下载 | 网站模板 | 网页特效 | 广告代码 | 网页素材 | 字体下载 | 书库 | 站长工具
会员投稿 投稿指南 RSS订阅
当前位置:主页>服务器类>Linux服务器>资讯:Linux关于消息队列的使用

Linux关于消息队列的使用

www.jz123.cn  2010-08-06   来源:   中国建站    责任编辑(袁袁)    我要投递新闻

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

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

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

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

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

  源代码来自华清远见:

  发送:

  #include

  #include

  #include

  #include

  #include

  #include

  #include

  #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 %dn", 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

  #include

  #include

  #include

  #include

  #include

  #include

  #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 %dn", 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号接收


上一篇:Linux服务器上如何对系统进行备份和恢复 下一篇:Linux中关于apt命令的应用

评论总数:0 [ 查看全部 ] 网友评论


关于我们隐私版权广告服务友情链接联系我们网站地图