Chinaunix首页 | 论坛 | 博客
  • 博客访问: 145548
  • 博文数量: 26
  • 博客积分: 645
  • 博客等级: 上士
  • 技术积分: 340
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-05 15:00
文章分类

全部博文(26)

文章存档

2014年(1)

2013年(1)

2011年(22)

2010年(1)

2009年(1)

我的朋友

分类: LINUX

2011-08-23 18:50:13

看了下网上的代码,发现XSI和POSIX的API形式不同,一开始没摸着头脑。这里忠于apue,用XSI进行实验。
后来又遇到了一些奇怪的问题,陆续会写上来。
----------------------------------------------
堆栈溢出问题没有复现,代码没备份,因此也不知道原因为何。。
下面是两个进程消息队列通信的例子。
创建队列:
  1. #include <stdio.h>
  2. #include <sys/msg.h>
  3. #include <sys/ipc.h>

  4. int main(void)
  5. {
  6.     int id;
  7.     id = msgget(IPC_PRIVATE, IPC_CREAT|0660);
  8.     printf("\n%d\n", id);
  9.     return 0;
  10. }
发送进程:
  1. #include <stdio.h>
  2. #include <sys/msg.h>
  3. #include <sys/ipc.h>

  4. int main(void)
  5. {
  6.     int id;
  7.     id = msgget(IPC_PRIVATE, IPC_CREAT|0660);
  8.     printf("\n%d\n", id);
  9.     return 0;
  10. }

  11. lisong@lisong:~/code/experiment/proc/IPC/msgqueue$
  12. lisong@lisong:~/code/experiment/proc/IPC/msgqueue$
  13. lisong@lisong:~/code/experiment/proc/IPC/msgqueue$
  14. lisong@lisong:~/code/experiment/proc/IPC/msgqueue$ more msgqs.c
  15. #include <stdio.h>
  16. #include <sys/msg.h>
  17. #include <sys/ipc.h>

  18. typedef struct mymsg{
  19.     long msgtype;
  20.     char mdata[100];
  21. }msg_t;

  22. int main(int argc, char *argv[])
  23. {
  24.     int ret;
  25.     int msgq_id;
  26.     char *msgstr;
  27.     msg_t msg;

  28.     if(argc < 3)
  29.     {
  30.         printf("please run this with msgqueue id and msgbody.\n");
  31.         return -1;
  32.     }
  33.     msgq_id = atoi(argv[1]);
  34.     if(msgq_id < 0)
  35.     {
  36.         printf("wrong queue id:%d.\n", msgq_id);
  37.         return -2;
  38.     }
  39.     printf("msgq_id:%d.\n", msgq_id);
  40.     msgstr = argv[2];
  41.     memset(&msg, 0, sizeof(msg));
  42.     msg.msgtype = 1;
  43.     strcpy(msg.mdata, msgstr);
  44.     ret = msgsnd(msgq_id, &msg, strlen(msg.mdata), IPC_NOWAIT);
  45.     printf("ret:%d.\n", ret);
  46.     return 0;
  47. }
接收进程:
  1. #include <stdio.h>
  2. #include <sys/msg.h>
  3. #include <sys/ipc.h>

  4. typedef struct mymsg{
  5.     long msgtype;
  6.     char mdata[100];
  7. }msg_t;

  8. int main(int argc, char *argv[])
  9. {
  10.     int s;
  11.     int msgq_id;
  12.     msg_t msg;

  13.     if(argc < 2)
  14.     {
  15.         printf("please run with msgqueue id.\n");
  16.         return -1;
  17.     }
  18.     msgq_id = atoi(argv[1]);
  19.     if(msgq_id < 0)
  20.     {
  21.         printf("wrong queue id:%d.\n", msgq_id);
  22.         return -2;
  23.     }
  24.     memset(&msg, 0, sizeof(msg));
  25.     printf("sizeof(msg):%d.\n", sizeof(msg));
  26.     s = msgrcv(msgq_id, &msg, 100, 0, IPC_NOWAIT);
  27.     printf("s:%d,msg.mdata:%s.\n", s, msg.mdata);
  28.     return 0;
  29. }

阅读(1397) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~