ivorakitin

IPC Message Queues

Dec 12th, 2025
65
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.58 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #include <sys/ipc.h>
  6. #include <sys/msg.h>
  7. #include <sys/wait.h>
  8.  
  9.  
  10. typedef struct msgbuf
  11. {
  12.     long mtype;
  13.     char mtext[100];
  14.     int pid;
  15.     double data;
  16. } message;
  17.  
  18. int main()
  19. {
  20.     key_t key = ftok(".", 1);
  21.     int msgid = msgget(key, IPC_CREAT | 0755);
  22.  
  23.     pid_t pid;
  24.     pid = fork();
  25.  
  26.     if (pid == -1)
  27.     {
  28.         perror("fork");
  29.         exit(EXIT_FAILURE);
  30.     }
  31.     else if (pid == 0)
  32.     {
  33.         message msg;
  34.         for (int i = 0; i < 10; i++)
  35.         {
  36.         msg.mtype = (i % 2) + 1;
  37.         msg.pid = getpid();
  38.         msg.data = i * 3.1415;
  39.         strcpy(msg.mtext, "Hello");
  40.         msgsnd(msgid, (message*) &msg, sizeof(msg), 0);
  41.         }
  42.     }
  43.     else if (pid > 0)
  44.     {
  45.         message msg;
  46.         wait(NULL);
  47.         printf("Retrieving messages with mtype=2\n");
  48.         for (int i = 0; i < 5; i++)
  49.         {
  50.             msgrcv(msgid, (message*) &msg, sizeof(msg), 2, 0);
  51.             printf("Parent pid: %d\n", getpid());
  52.             printf("Message received: %s %lf %l\n", msg.mtext, msg.data, msg.mtype);
  53.             printf("Child PID: %d\n", msg.pid);
  54.         }
  55.        
  56.         printf("Retrieving messages with mtype=1\n");        
  57.         for (int i = 0; i < 5; i++)
  58.         {
  59.             msgrcv(msgid, (message*) &msg, sizeof(msg), 1, 0);
  60.             printf("Parent pid: %d\n", getpid());
  61.             printf("Message received: %s %lf %l\n", msg.mtext, msg.data, msg.mtype);
  62.             printf("Child PID: %d\n", msg.pid);
  63.         }        
  64.     }
  65.     return 0;
  66. }
  67.  
Tags: ipc
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment