Advertisement
Nasekoma

12-4

Dec 15th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.20 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <sys/wait.h>
  5. #include <sys/ipc.h>
  6. #include <sys/sem.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>
  9.  
  10. enum
  11. {
  12.     BASE = 10,
  13.     NAMELEN = 20
  14. };
  15.  
  16. int
  17. main(int argc, char *argv[])
  18. {
  19.     if (argc < 2) {
  20.         return 0;
  21.     }
  22.     int count = strtol(argv[1], NULL, BASE);
  23.     int semid = semget(IPC_PRIVATE, count + 1, 0666|IPC_CREAT);
  24.     int i;
  25.     for (i = 0; i < count; i++) {
  26.         if (!fork()) {
  27.             semop(semid, (struct sembuf[]){{count, 1, 0}}, 1);
  28.             int num;
  29.             while (semop(semid, (struct sembuf[]){{i, -1, 0}}, 1) >= 0) {
  30.                 if (scanf("%d", &num) <= 0) {
  31.                     semctl(semid, 0, IPC_RMID, 0);
  32.                     break;
  33.                 }
  34.                 printf("%d %d\n", i, num);
  35.                 fflush(stdout);
  36.                 num = num >= 0 ? num % count : num % count + count;
  37.                 semop(semid, (struct sembuf[]){{num % count, 1, 0}}, 1);
  38.             }
  39.             _exit(0);
  40.         }
  41.     }
  42.     semop(semid, (struct sembuf[]){{count, -count, 0}}, 1);
  43.     semop(semid, (struct sembuf[]){{0, 1, 0}}, 1);
  44.     while (wait(NULL) >= 0);
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement