而後,無恥又無聊的照書上抄了一個例子:ide
/**recv**/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/msg.h> 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 <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/msg.h> #define MAX_TEXT 512 struct 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
函數