Advertisement
Guest User

Untitled

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