Tobiahao

S01_LAB03_02

Nov 14th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. /*
  2. Zmodyfikuj zadanie pierwsze, tak aby proces tworzył potomka
  3. i komunikował się z nim przy użyciu kolejki.
  4. */
  5.  
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <sys/types.h>
  9. #include <sys/ipc.h>
  10. #include <sys/msg.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include <wait.h>
  14.  
  15. #define MESSAGE_TO_SEND "Jakas inna wiadomosc"
  16. #define BUFFER_SIZE 128
  17.  
  18. struct msgbuf {
  19.     long mtype;
  20.     char mtext[BUFFER_SIZE];
  21. };
  22.  
  23. void send_message(int id)
  24. {
  25.     struct msgbuf send_buffer;
  26.  
  27.     send_buffer.mtype = 1;
  28.     memset(send_buffer.mtext, '\0', BUFFER_SIZE-1);
  29.     strncpy(send_buffer.mtext, MESSAGE_TO_SEND, BUFFER_SIZE-1);
  30.  
  31.     if(msgsnd(id, &send_buffer, strlen(send_buffer.mtext), 0) == -1){
  32.         perror("msgsnd");
  33.         exit(EXIT_FAILURE);
  34.     }
  35. }
  36.  
  37. void recv_message(int id)
  38. {
  39.     struct msgbuf recv_buffer;
  40.     memset(recv_buffer.mtext, '\0', BUFFER_SIZE-1);
  41.     if(msgrcv(id, &recv_buffer, sizeof(recv_buffer.mtext), 1, 0) == -1){
  42.         perror("msgrecv");
  43.         exit(EXIT_FAILURE);
  44.     }
  45.  
  46.     printf("Przeslana wiadomosc: %s\n", recv_buffer.mtext);
  47. }
  48.  
  49. int main(void)
  50. {
  51.     int id;
  52.     pid_t pid;
  53.     if((id = msgget(IPC_PRIVATE, 0600 | IPC_CREAT)) == -1){
  54.         perror("msgget");
  55.         return EXIT_FAILURE;
  56.     }
  57.  
  58.     pid = fork();
  59.     if(pid == -1){
  60.         perror("fork");
  61.         return EXIT_FAILURE;
  62.     }
  63.     else if(pid == 0){
  64.         send_message(id);
  65.     }
  66.     else{
  67.         wait(NULL);
  68.         recv_message(id);
  69.         if(msgctl(id, IPC_RMID, 0) == -1){
  70.             perror("msgctl");
  71.             return EXIT_FAILURE;
  72.         }
  73.  
  74.  
  75.     }
  76.  
  77.     return EXIT_SUCCESS;
  78. }
Add Comment
Please, Sign In to add comment