Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.91 KB | None | 0 0
  1. /* touch queue; gcc -Wall -Wextra -pedantic -std=c99 -o a a.c && a */
  2. #include <errno.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <sys/types.h>
  7. #include <sys/ipc.h>
  8. #include <sys/msg.h>
  9. #include <sys/wait.h>
  10. #include <unistd.h>
  11.  
  12. typedef struct Mymsg {
  13.     long mtype;     /* Message type */
  14.     char mtext[20]; /* Message body */
  15. } Mymsg;
  16.  
  17.  
  18. int main() {
  19.     key_t key = ftok("queue", 'x');
  20.     int id = msgget(key, IPC_CREAT);
  21.     if (id == -1) {
  22.         printf("msgget error");
  23.         exit(EXIT_FAILURE);
  24.     }
  25.  
  26.     pid_t child_pid = fork();
  27.     if (child_pid == -1) {
  28.         perror("fork");
  29.         exit(EXIT_FAILURE);
  30.     }
  31.  
  32.     if (child_pid == 0) {
  33.         printf("CHILD PROCESS\n");
  34.  
  35.         Mymsg message;
  36.         message.mtype = 1;
  37.         strcpy(message.mtext, "test");
  38.         if (msgsnd(id, &message, sizeof(message)-sizeof(long), 0) == -1) {
  39.             perror("msgsnd");
  40.             exit(EXIT_FAILURE);
  41.         }
  42.  
  43.         exit(EXIT_SUCCESS);
  44.     }
  45.     else
  46.     {
  47.         int status;
  48.         if (waitpid(child_pid, &status, 0) == -1) {
  49.             perror("waitpid");
  50.             exit(EXIT_FAILURE);
  51.         }
  52.         if (WIFSIGNALED(status)) {
  53.             fprintf(stderr, "Child killed by signal %d\n", WTERMSIG(status));
  54.             exit(EXIT_FAILURE);
  55.         }
  56.         if (!WEXITSTATUS(status)) {
  57.             fprintf(stderr, "Child exited with error %d\n", WEXITSTATUS(status));
  58.             exit(EXIT_FAILURE);
  59.         }
  60.  
  61.         printf("PARENT PROCESS\n");
  62.  
  63.         Mymsg message;
  64.         if (msgrcv(id, &message, sizeof(message)-sizeof(long), 1, 0) == -1) {
  65.             perror("msgrcv");
  66.             exit(EXIT_FAILURE);
  67.         }
  68.  
  69.         printf("READ: %s\n", message.mtext);
  70.  
  71.         if (msgctl(id, IPC_RMID, 0) == -1) {
  72.             perror("msgctl");
  73.             exit(EXIT_FAILURE);
  74.         }
  75.  
  76.         exit(EXIT_SUCCESS);
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement