Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3425501
  • 博文数量: 198
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 7246
  • 用 户 组: 普通用户
  • 注册时间: 2013-01-23 18:56
个人简介

将晦涩难懂的技术讲的通俗易懂

文章分类

全部博文(198)

文章存档

2023年(9)

2022年(4)

2021年(12)

2020年(8)

2019年(18)

2018年(19)

2017年(9)

2016年(26)

2015年(18)

2014年(54)

2013年(20)

分类: LINUX

2013-04-12 21:18:46

在于都apue的消息队列部分时,发现书中并没有相关的实例,这里自己写了一个简单的小例子,加深对消息队列的理解,子进程从终端读取消息传入消息队列,
父进程,读取消息队列中的消息,并打印到终端。

点击(此处)折叠或打开

  1. #include "apue.h"
  2. #include <sys/msg.h>
  3. #include <sys/ipc.h>
  4. struct mymesg{ //定义消息结构
  5.   long mtype; //消息类型
  6.   char mtext[512]; //消息实际数据
  7. };
  8. int
  9. main(void)
  10. {
  11.   struct mymesg mesg;
  12.   int pid;
  13.   int mesgno;
  14.   mesg.mtype=1;
  15.   int running=1;
  16.   ssize_t m;
  17.   key_t key;
  18.   if((key=ftok("megqueue.c",'a'))==-1)//使用ftok生成创建消息队列要使用的key,注意第一个参数必须是一个现存文件的路径
  19.      printf("ftok error\n");
  20.   if((mesgno=msgget(key,IPC_CREAT|S_IRUSR|S_IWUSR))==-1)//创建消息队列
  21.     printf("creat message queue error\n");
  22.   printf("messgae no:%d\n",mesgno);//输出消息队列标示符
  23.   if((pid=fork())<0)
  24.     printf("fork error\n");
  25.   else if(pid==0) //子进程从终端读取消息传入消息队列
  26.    {
  27.     while(running)
  28.     {
  29.      if(fgets(mesg.mtext,512,stdin)!=NULL)
  30.      {printf("%s\n",mesg.mtext);    msgsnd(mesgno,&mesg,521,0);}
  31.      else
  32.      {
  33.             printf("getmsg error\n");
  34.         break;
  35.               }    
  36.     }
  37.    }
  38.   else //父进程,读取消息队列中的消息,并打印到终端
  39.    {
  40.     while((m=msgrcv(mesgno,&mesg,512,0,MSG_NOERROR))!=-1)
  41.         printf("parent:%s\n",mesg.mtext);
  42.        printf("over\n");
  43.    }
  44.   exit(0);
  45. }
运行结果:

注意CTRL+C结束进程后,消息队列并没有删除
阅读(2690) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~