Advertisement
Guest User

Untitled

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