Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <stdlib.h>
- #include <sys/ipc.h>
- #include <sys/msg.h>
- #include <sys/wait.h>
- typedef struct msgbuf
- {
- long mtype;
- char mtext[100];
- int pid;
- double data;
- } message;
- int main()
- {
- key_t key = ftok(".", 1);
- int msgid = msgget(key, IPC_CREAT | 0755);
- pid_t pid;
- pid = fork();
- if (pid == -1)
- {
- perror("fork");
- exit(EXIT_FAILURE);
- }
- else if (pid == 0)
- {
- message msg;
- for (int i = 0; i < 10; i++)
- {
- msg.mtype = (i % 2) + 1;
- msg.pid = getpid();
- msg.data = i * 3.1415;
- strcpy(msg.mtext, "Hello");
- msgsnd(msgid, (message*) &msg, sizeof(msg), 0);
- }
- }
- else if (pid > 0)
- {
- message msg;
- wait(NULL);
- printf("Retrieving messages with mtype=2\n");
- for (int i = 0; i < 5; i++)
- {
- msgrcv(msgid, (message*) &msg, sizeof(msg), 2, 0);
- printf("Parent pid: %d\n", getpid());
- printf("Message received: %s %lf %l\n", msg.mtext, msg.data, msg.mtype);
- printf("Child PID: %d\n", msg.pid);
- }
- printf("Retrieving messages with mtype=1\n");
- for (int i = 0; i < 5; i++)
- {
- msgrcv(msgid, (message*) &msg, sizeof(msg), 1, 0);
- printf("Parent pid: %d\n", getpid());
- printf("Message received: %s %lf %l\n", msg.mtext, msg.data, msg.mtype);
- printf("Child PID: %d\n", msg.pid);
- }
- }
- return 0;
- }
Advertisement