Created
August 16, 2013 17:19
-
-
Save ryochack/6251746 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // process communication using message queue | |
| #include <sys/types.h> | |
| #include <sys/ipc.h> | |
| #include <sys/msg.h> | |
| #include <unistd.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #define MSGLEN (16) | |
| struct msgbuf { | |
| long type; | |
| char text[MSGLEN]; | |
| }; | |
| void die(const char* msg) { | |
| perror(msg); | |
| exit(1); | |
| } | |
| int main() { | |
| int i; | |
| // get key | |
| key_t msgkey = ftok("temp", 'A'); | |
| if (msgkey == -1) die("ftok()"); | |
| int msgqid = msgget(msgkey, IPC_CREAT); | |
| if (msgqid == -1) die("msgget()"); | |
| pid_t pid = fork(); | |
| if (pid < 0) { | |
| die("fork()"); | |
| } else if (pid == 0) { | |
| // child process | |
| struct msgbuf msgs[6]; | |
| const char* texts[] = {"first", "second", "third", "forth", "fifth", "q"}; | |
| while (1) { | |
| msgs[i].type = 1; | |
| strcpy(msgs[i].text, texts[i]); | |
| if (msgsnd(msgqid, &msgs[i], MSGLEN, 0) == -1) die("msgsnd()"); | |
| printf("snd %s\n", msgs[i].text); | |
| if (msgs[i].text[0] == 'q') break; | |
| i++; | |
| } | |
| return 1; | |
| } else { | |
| // parent process | |
| struct msgbuf msg; | |
| while (1) { | |
| if (msgrcv(msgqid, &msg, MSGLEN, 0, 0) == -1) die("msgrcv()"); | |
| printf("rcv %s\n", msg.text); | |
| if (msg.text[0] == 'q') break; | |
| } | |
| return 2; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment