单向IPC通信
vi demo6.c
1 #include <string.h>
2 #include<stdio.h>
3 #include <sys/msg.h>
4 #include <errno.h>
5
6 // int msgget(key_t key, int msgflg);
7 // int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
8 struct msgbuf {
9 long mtype; /* message type, must be > 0 */
10 char mtext[128]; /* message data */
11 };
12
13 int main()
14 {
15 key_t key;
16 key = ftok(".",4);
17 int msgId;
18 msgId = msgget(key,IPC_CREAT|0600);
19 if(msgId == -1){
20 perror("why");
21 }
22 struct msgbuf buf = {888,"hello,my name is GM"};
23 msgsnd(msgId,&buf,strlen(buf.mtext),0);
24 printf("snd ok\n");
25
26 return 0;
27 }
~
vi demo7.c
1 #include<stdio.h>
2 #include <sys/msg.h>
3 #include <errno.h>
4
5 struct msgbuf {
6 long mtype; /* message type, must be > 0 */
7 char mtext[128]; /* message data */
8 };
9
10 int main()
11 {
12 key_t key;
13 key = ftok(".",4);
14 int msgId;
15 msgId = msgget(key,IPC_CREAT|0600);
16 if(msgId == -1){
17 perror("why");
18 }
19
20 // int msgId;
21 struct msgbuf buf;
22 // msgsnd(msgId,&buf,sizeof(buf.mtext),0);
23 // ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
24 msgrcv(msgId,&buf,sizeof(buf.mtext),888,0);
25 printf("msgcontext:%s\n",buf.mtext);
26
27 return 0;
28 }
双向IPC通信
demo8.c
1 #include <string.h>
2 #include<stdio.h>
3 #include <sys/msg.h>
4 #include <errno.h>
5
6 // int msgget(key_t key, int msgflg);
7 // int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
8 struct msgbuf {
9 long mtype; /* message type, must be > 0 */
10 char mtext[128]; /* message data */
11 };
12
13 int main()
14 {
15 key_t key;
16 key = ftok(".",4);
17 int msgId;
18 msgId = msgget(key,IPC_CREAT|0600);
19 if(msgId == -1){
20 perror("why");
21 }
22 struct msgbuf buf = {888,"hello,my name is GM"};
23 msgsnd(msgId,&buf,strlen(buf.mtext),0);
24
25 struct msgbuf readbuf;
26 msgrcv(msgId,&readbuf,sizeof(readbuf.mtext),999,0);
27 printf("msgcontext:%s\n",readbuf.mtext);
28 printf("snd ok\n");
29
30 return 0;
31 }
~
demo9.c
1 #include <string.h>
2 #include<stdio.h>
3 #include <sys/msg.h>
4 #include <errno.h>
5
6 struct msgbuf {
7 long mtype; /* message type, must be > 0 */
8 char mtext[128]; /* message data */
9 };
10
11 int main()
12 {
13 key_t key;
14 key = ftok(".",4);
15 int msgId;
16 msgId = msgget(key,IPC_CREAT|0600);
17 if(msgId == -1){
18 perror("why");
19 }
20
21 // int msgId;
22 struct msgbuf buf;
23 // msgsnd(msgId,&buf,sizeof(buf.mtext),0);
24 // ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
25 msgrcv(msgId,&buf,sizeof(buf.mtext),888,0);
26 printf("msgcontext:%s\n",buf.mtext);
27
28 struct msgbuf sndBuf = {999,"my name is guoming"};
29 msgsnd(msgId,&sndBuf,strlen(sndBuf.mtext),0);
30
31 return 0;
32 }