Advertisement
Guest User

Untitled

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