使用消息队列完成两个进程之间相互通信
1 #include<head.h>
2 struct msgbuf
3 {
4 long mtype; //消息类型
5 char mtext[1024]; //消息正文
6 };
7 //定义一个宏,表示正文大小
8 #define SIZE (sizeof(struct msgbuf) - sizeof(long))
9
10 int main(int argc, const char *argv[])
11 {
12 key_t key = 0;
13 if((key = ftok("/", 't')) == -1)
14 {
15 perror("fork error");
16 return -1;
17 }
18 //使用key值创建一个消息队列
19 int msqid = 0;
20 if((msqid=msgget(key, IPC_CREAT|0664)) == -1)
21 {
22 perror("msgget error");
23 return -1;
24 }
25 pid_t pid;
26 pid=fork();
27 if(pid>0)
28 {
29 //定义一个消息类型的容器
30 struct msgbuf buf = {.mtype=1};
31 //循环向消息队列中存放数据
32 while(1)
33 {
34 scanf("%s", buf.mtext);
35 getchar(); //吸收回车
36 //将消息存放到消息队列中
37 msgsnd(msqid, &buf, SIZE, 0);
38 if(strcmp(buf.mtext, "quit") == 0)
39 {
40 break;
41 }
42 }
43 //删除消息队列
44 if(msgctl(msqid, IPC_RMID, NULL) == -1)
45 {
46 perror("msgctl error");
47 return -1;
48 }
49 }
50 else if(pid==0)
51 {
52 //定义一个消息类型的容器
53 struct msgbuf buf={.mtype=2};
54 //循环向消息队列中存放数据
55 while(1)
56 {
57 //从消息队列中读取消息
58 msgrcv(msqid, &buf, SIZE, 2,0);
59 //第一个0表示无视类型,每次都取第一个消息
60 //第二个0表示阻塞形式接收消息
61 printf("收到消息为:%s\n", buf.mtext);
62 if(strcmp(buf.mtext, "quit") == 0)
63 {
64 break;
65 }
66 }
67 //删除消息队列
68 if(msgctl(msqid, IPC_RMID, NULL) == -1)
69 {
70 perror("msgctl error");
71 return -1;
72 }
73 }
74 else
75 {
76 perror("fork error");
77 return -1;
78 }
79 return 0;
80 }
1 #include<head.h>
2 struct msgbuf
3 {
4 long mtype; //消息类型
5 char mtext[1024]; //消息正文
6 };
7 //定义一个宏,表示正文大小
8 #define SIZE (sizeof(struct msgbuf) - sizeof(long))
9
10 int main(int argc, const char *argv[])
11 {
12 key_t key = 0;
13 if((key = ftok("/", 't')) == -1)
14 {
15 perror("fork error");
16 return -1;
17 }
18 //使用key值创建一个消息队列
19 int msqid = 0;
20 if((msqid=msgget(key, IPC_CREAT|0664)) == -1)
21 {
22 perror("msgget error");
23 return -1;
24 }
25 pid_t pid;
26 pid=fork();
27 if(pid>0)
28 {
29 //定义一个消息类型的容器
30 struct msgbuf buf={.mtype=1};
31
32 //循环向消息队列中存放数据
33 while(1)
34 {
35 //从消息队列中读取消息
36 msgrcv(msqid, &buf, SIZE, 1, 0);
37 //第一个0表示无视类型,每次都取第一个消息
38 //第二个0表示阻塞形式接收消息
39 printf("收到消息为:%s\n", buf.mtext);
40 if(strcmp(buf.mtext, "quit") == 0)
41 {
42 break;
43 }
44 }
45 //删除消息队列
46 if(msgctl(msqid, IPC_RMID, NULL) == -1)
47 {
48 perror("msgctl error");
49 return -1;
50 }
51 }
52 else if(pid==0)
53 {
54 //定义一个消息类型的容器
55 struct msgbuf buf = {.mtype=2};
56 //循环向消息队列中存放数据
57 while(1)
58 {
59 scanf("%s", buf.mtext);
60 getchar(); //吸收回车
61 //将消息存放到消息队列中
62 msgsnd(msqid, &buf, SIZE, 0);
63 if(buf.mtext=="quit")
64 {
65 break;
66 }
67 } //删除消息队列
68 if(msgctl(msqid, IPC_RMID, NULL) == -1)
69 {
70 perror("msgctl error");
71 return -1;
72 }
73 }
74 else
75 {
76 perror("fork error");
77 return -1;
78 }
79 return 0;
80 }