Advertisement
Guest User

Untitled

a guest
Dec 14th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <sys/wait.h>
  6. #include <signal.h>
  7. #include <sys/ipc.h>
  8. #include <sys/sem.h>
  9. #include <sys/shm.h>
  10. #include <sys/msg.h>
  11. #include <sys/types.h>
  12.  
  13. enum { BASE = 10 };
  14.  
  15.  
  16. int main(int argc, char *argv[]) {
  17. setbuf(stdin, NULL);
  18. //int count = (int) strtol(argv[1], NULL, BASE);
  19. int count = 3;
  20. int sem_id = semget(IPC_PRIVATE, count + 1, 0666 | IPC_CREAT | IPC_EXCL);
  21. if (sem_id < 0) {
  22. exit(1);
  23. }
  24. pid_t pid[count];
  25. for (int i = 0; i < count; i++) {
  26. pid[i] = fork();
  27. if (pid[i] == 0) {
  28. while (1) {
  29. if ((semop(sem_id, (struct sembuf[]){{count, -1, IPC_NOWAIT}}, 1) >= 0) || (semop(sem_id, (struct sembuf[]){{i, -1, 0}}, 1) >= 0)) {
  30. if (semop(sem_id, (struct sembuf[]){{i, -1, 0}}, 1) >= 0) {
  31. int tmp;
  32. if (scanf("%d", &tmp) == EOF) {
  33. semop(sem_id,(struct sembuf[]){{count, count, 0}},1);
  34. }
  35. printf("%d %d\n", i, tmp);
  36. tmp = ((tmp % count) + count) % count;
  37. semop(sem_id,(struct sembuf[]){{tmp, 2, 0}},1);
  38. } else {
  39. exit(0);
  40. }
  41. }
  42. /*if (semop(sem_id, (struct sembuf[]){{count, -1, 0}}, 1) >= 0) {
  43. exit(0);
  44. }*/
  45. }
  46.  
  47.  
  48. /*while (semop(sem_id, (struct sembuf[]){{i, -1, 0}}, 1) >= 0) {
  49. int tmp;
  50. if (scanf("%d", &tmp) == EOF) {
  51. semop(sem_id,(struct sembuf[]){{count, 1, 0}},1);
  52. }
  53. printf("%d %d\n", i, tmp);
  54. tmp = ((tmp % count) + count) % count;
  55. semop(sem_id,(struct sembuf[]){{tmp, 1, 0}},1);
  56.  
  57. } */
  58.  
  59. } else if (pid[i] < 0) {
  60. exit(1);
  61. }
  62.  
  63. }
  64. semop(sem_id, (struct sembuf[]) {{0, 2, 0}}, 1);
  65. while (wait(NULL) > 0) {
  66.  
  67. }
  68. semctl(sem_id, 0, IPC_RMID);
  69. return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement