Advertisement
Guest User

Untitled

a guest
Dec 12th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <sys/types.h>
  4. #include <sys/msg.h>
  5. #include<unistd.h>
  6. #include<sys/wait.h>
  7.  
  8. struct msgbuf1 {
  9.  
  10. long mtype;
  11. char mtext;
  12. };
  13. int msgCreate(key_t key)
  14. {
  15. int msgId = msgget(key,IPC_CREAT|0700);
  16. if( msgId == -1)
  17. {
  18. perror("Blad tworzenia kolejki komunikatow");
  19. exit(1);
  20. }
  21. return msgId;
  22. }
  23. int msgOpen(key_t key)
  24. {
  25. int msgId = msgget(key,IPC_CREAT|0600) ;
  26. if( msgId == -1)
  27. {
  28. perror("Blad uzyskania dostepu do kolejki komunikatow");
  29. exit(1);
  30. }
  31. return msgId;
  32. }
  33. void msgRemove(int msgId)
  34. {
  35. if(msgctl(msgId,IPC_RMID,NULL) == -1)
  36. {
  37. perror("Blad usuniecia kolejki komunikatow");
  38. exit(-1);
  39. }
  40. }
  41. void msgSend(int msgid, void*msgp,int msgsz)
  42. {
  43. if(msgsnd(msgid,msgp,msgsz,IPC_NOWAIT) == -1)
  44. {
  45. perror("Blad nadania komunikatu");
  46. exit(1);
  47. }
  48. }
  49. void msgReceive(int msgid, void*msgp,int msgsz,long msgtyp)
  50. {
  51.  
  52. if(msgrcv(msgid,msgp,msgsz,msgtyp,IPC_NOWAIT) == -1)
  53. {
  54. perror("Blad odebrania komunikatu");
  55. exit(1);
  56. }
  57. }
  58. int main()
  59. {
  60.  
  61. int key;
  62. key = ftok(".",'2');
  63.  
  64. int pid = fork();
  65.  
  66. msgCreate(key);
  67. int msgid = msgOpen(key);
  68.  
  69. if(pid == 0)
  70. {
  71. struct msgbuf1 element2;
  72. msgReceive(msgid,&element2,100,5);
  73. printf("Element: %c \n", element2.mtext);
  74.  
  75.  
  76. }
  77. else
  78. {
  79.  
  80. struct msgbuf1 element;
  81. element.mtype = 5;
  82. element.mtext = 'A';
  83. msgSend(msgid,&element,sizeof(element.mtext));
  84.  
  85. }
  86.  
  87. wait(NULL);
  88. msgRemove(msgid);
  89. return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement