Advertisement
Guest User

Untitled

a guest
Dec 4th, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/wait.h>
  5. #include <sys/msg.h>
  6.  
  7. struct m
  8. {
  9. long type;
  10. long end;
  11. };
  12.  
  13.  
  14. void doson(int key, int son, int brother)
  15. {
  16. struct m msg;
  17. int val;
  18. if(!fork()) {
  19. int msqid = msgget(key, 0);
  20. while(1) {
  21. msgrcv(msqid, &msg, sizeof(msg.end), son, 0);
  22. if(msg.end == 1) {
  23. _exit(0);
  24. }
  25. if(scanf("%d", &val) < 0) {
  26. msg.end = 1;
  27. msg.type = brother;
  28. msgsnd(msqid, &msg, sizeof(msg.end), 0);
  29. _exit(0);
  30. }
  31. printf("%d %d\n",son, val);
  32. fflush(stdout);
  33. msg.type = brother;
  34. msgsnd(msqid, &msg, sizeof(msg.end), 0);
  35. }
  36. }
  37. }
  38.  
  39. int
  40. main(void)
  41. {
  42. struct m msg;
  43. key_t key = ftok("file1.txt", 0);
  44. int msqid = msgget(key, IPC_CREAT | 0644);
  45. msg.type = 1;
  46. msg.end = 0;
  47. msgsnd(msqid, &msg, sizeof(msg.end), 0);
  48. doson(key, 1, 2);
  49. doson(key, 2, 1);
  50. wait(NULL);
  51. wait(NULL);
  52. msgctl(msqid, IPC_RMID, 0);
  53. return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement