您的位置:首页 > 运维架构 > Linux

Linux C 进程间的IPC通信 之 消息队列(2)

2017-06-18 10:30 295 查看
Linux C 进程间的IPC通信 之 消息队列

                         双向通信

代码:(进程1)

1 #include <stdio.h>
2 #include <sys/msg.h>
3 #include <string.h>
4
5 struct msgbuf
6 {
7 long type; //long型的type标识
8 char content[116];
9 char flag[4];
10 };
11
12 int main()
13 {
14 int key;
15 int msgid;
16 int pid;
17 struct msgbuf sndbuf, rcvbuf;
18
19 int rcvLen;
20
21 key = ftok("./a",'b'); //创建 key值
22 msgid = msgget(key, IPC_CREAT | 0777); //创建 消息队列
23 printf("message queue: msgid = %d key = %X\n", msgid, key);
24
25 pid = fork(); //创建父子进程
26 if(pid > 0) //server端 的父进程 写(发送)
27 {
28 sndbuf.type = 333; //server端 发送数据的标识
29 while(1)
30 {
31 printf("server send message: ");
32 //写到哪里去、写多少个、从哪里写
33 fgets(sndbuf.content, 116, stdin);//从键盘输入到缓存变量
34 //发给谁、发什么、发多少、参数0为阻塞模式
35 msgsnd(msgid, &sndbuf, strlen(sndbuf.content), 0);//发送给消息队列
36 }
37 }
38
39 if( pid == 0) //server端 的子进程 读(接收)
40 {
41 while(1)
42 {
43 memset(rcvbuf.content,0,116); //清空 接收缓存
44 //从哪里读、读到哪里去、读多少个、数据标识、参数0为阻塞模式
45 rcvLen = msgrcv(msgid, &rcvbuf, 116, 555, 0); //读取消息队列
46 printf("server receive message[%d bytes]: %s", rcvLen - 1, rcvbuf.content);
47 }
48 }
49
50
51 return 0;
52 }

代码:(进程2)
1 #include <stdio.h>
2 #include <sys/msg.h>
3 #include <string.h>
4
5 struct msgbuf
6 {
7 long type;
8 char content[116];
9
10 };
11
12 int main()
13 {
14 int key;
15 int msgid;
16 struct msgbuf sndbuf, rcvbuf;
17 int pid;
18
19 key = ftok("./a",'b'); //创建key值
20 if(key < 0)
21 {
22 printf("client create key failed.\n");
23 return -1;
24 }
25
26 msgid = msgget(key, IPC_CREAT | 0777); //创建消息队列
27 if(msgid < 0)
28 {
29 printf("client message queue create failure.\n");
30 return -2;
31 }
32 printf("client message queue: msgid = %d key = %X\n", msgid, key);
33 system("ipcs -q"); //查看消息队列
34
35 pid = fork(); //创建父子进程
36 if(pid > 0) //client端的父进程 读(接收)
37 {
38 while(1)
39 {
40 memset(rcvbuf.content, 0, 116); //清空 接收缓存
41 msgrcv(msgid, &rcvbuf, 116, 333, 0); //读取消息队列
42 printf("client receive message: %s", rcvbuf.content);
43 }
44 }
45 if(pid == 0) //client端的父进程 写(发送)
46 {
47 sndbuf.type = 555; //数据标识
48 while(1)
49 {
50 printf("client send message: ");
51 fgets(sndbuf.content, 116, stdin); //键盘输入
52 msgsnd(msgid, &sndbuf, strlen(sndbuf.content), 0); //写入消息队列
53 }
54 }
55
56 return 0;
57 }

执行:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux c语言