Tobiahao

S01_LAB03_05b

Nov 14th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.07 KB | None | 0 0
  1. /*
  2. Napisz dwa programy: pierwszy wyśle kilka komunikatów o losowo wybranym typie (przyjmijmy, że typy komunikatów należą do przedziału[1,5]), a drugi będzie je odbierze w porządku malejącym lub rosnącym,
  3. ze względu na wartość typu.
  4. */
  5.  
  6. // Program drugi
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <sys/types.h>
  11. #include <sys/ipc.h>
  12. #include <sys/msg.h>
  13. #include <time.h>
  14.  
  15. #define FTOK_KEY "/tmp"
  16. #define FTOK_NUMBER 712
  17.  
  18. struct msgbuf {
  19.     long mtype;
  20.     int number;
  21. };
  22.  
  23. int main(void)
  24. {
  25.     key_t key;
  26.     int id;
  27.    
  28.     if((key = ftok(FTOK_KEY, FTOK_NUMBER)) == -1){
  29.         perror("ftok");
  30.         return EXIT_FAILURE;
  31.     }
  32.  
  33.     if((id = msgget(key, 0600 | IPC_CREAT)) == -1){
  34.         perror("msgget");
  35.         return EXIT_FAILURE;
  36.     }
  37.  
  38.     for(int i = 1; i <= 5; i++){
  39.         struct msgbuf buffer;
  40.        
  41.         if(msgrcv(id, &buffer, sizeof(buffer.number), i, 0) == -1){
  42.             perror("msgrcv");
  43.             return EXIT_FAILURE;
  44.         }  
  45.         printf("Komunikat: %d\n", buffer.number);
  46.     }
  47.  
  48.     if(msgctl(id, IPC_RMID, 0) == -1){
  49.         perror("msgctl");
  50.         return EXIT_FAILURE;
  51.     }
  52.  
  53.     return EXIT_SUCCESS;
  54. }
Add Comment
Please, Sign In to add comment