然后,无耻又无聊的照书上抄了一个例子:
/**recv**/#include#include #include #include #include #include struct my_msg_st{ long int my_msg_type; char sometext[BUFSIZ];};int main(){ int running = 1; int msgid; struct my_msg_st msg; long int msg_to_recv = 0; msgid = msgget( (key_t)1234, 0666 | IPC_CREAT); if (msgid < 0) { fprintf(stderr, "msgget failed with error: %d \n", errno); exit(EXIT_FAILURE); } while (running) { if (msgrcv(msgid, (void*)&msg, BUFSIZ, msg_to_recv, 0) == -1) { fprintf(stderr, "msgrcv failed with error %d \n", errno); exit(EXIT_FAILURE); } printf("You wrote: %s", msg.sometext); if (strncmp(msg.sometext, "end", 3) == 0) { running = 0; } } if (msgctl(msgid, IPC_RMID, 0) < 0) { fprintf(stderr, "msgctl(IPC_RMID) failed\n"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS);}/**send**/#include #include #include #include #include #include #define MAX_TEXT 512struct my_msg_st{ long int my_msg_type; char sometext[BUFSIZ];};int main(){ int running = 1; int msgid; struct my_msg_st msg; char buf[BUFSIZ]; msgid = msgget( (key_t)1234, 0666 | IPC_CREAT); if (msgid < 0) { fprintf(stderr, "msgget failed with error: %d \n", errno); exit(EXIT_FAILURE); } while (running) { printf("Enter some text: "); fgets(buf, BUFSIZ, stdin); /* fgets add \0 to the end of the buf */ msg.my_msg_type = 1; strcpy(msg.sometext, buf); if (msgsnd(msgid, (void *)&msg, MAX_TEXT, 0) < 0) { fprintf(stderr, "msgsnd failed\n"); exit(EXIT_FAILURE); } if (strncmp(buf, "end", 3)==0) { running = 0; } } exit(EXIT_SUCCESS);}
结果:
chenqi@chenqi-laptop ~/MyPro/CFiles/IPC/msg_queue $ ./recv & [1] 19084 chenqi@chenqi-laptop ~/MyPro/CFiles/IPC/msg_queue $ ./send Enter some text: hello Enter some text: You wrote: hello nice Enter some text: You wrote: nice to Enter some text: You wrote: to meet Enter some text: You wrote: meet you Enter some text: You wrote: you end You wrote: end [1]+ Done ./recv