Advertisement
wowonline

Untitled

Dec 15th, 2021
773
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.99 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <inttypes.h>
  3. #include <sys/sem.h>
  4. #include <sys/shm.h>
  5. #include <sys/ipc.h>
  6. #include <unistd.h>
  7. #include <stdio.h>
  8.  
  9.  
  10. enum { DECIMAL_BASE = 10 };
  11.  
  12. int
  13. main(int argc, char *argv[])
  14. {
  15.     pid_t pid;
  16.     int nproc = strtol(argv[1], NULL, DECIMAL_BASE);
  17.     int key = strtol(argv[2], NULL, DECIMAL_BASE);
  18.     int maxval = strtoull(argv[3], NULL, DECIMAL_BASE);
  19.     int shm_id, sem_id;
  20.     if ((shm_id = shmget(key, 3 * sizeof(maxval), IPC_CREAT | 0600)) == -1) {
  21.         return 1;
  22.     }
  23.     int *memory = shmat(shm_id, NULL, 0);
  24.     if (memory == NULL) {
  25.         return 1;
  26.     }
  27.     if ((sem_id = semget(key, nproc, IPC_CREAT | 0600)) == -1) {
  28.         return 1;
  29.     }
  30.  
  31.     for (int i = 0; i < nproc; ++i) {
  32.         pid = fork();
  33.         if (pid == -1) {
  34.             return 1;
  35.         } else if (!pid) {
  36.             int value, target;
  37.             struct sembuf lock = {i, -1, 0};
  38.             struct sembuf unlock = {-1, 1, 0};
  39.             while (1) {
  40.                 if (semop(sem_id, &lock, 1) == -1) {
  41.                     _exit(0);
  42.                 }
  43.                 value = memory[1];
  44.                 value++;
  45.                 printf("%d %d %d\n", memory[0], memory[1], memory[2]);
  46.                 fflush(stdout);
  47.                 if (value > maxval) {
  48.                     semctl(sem_id, 1, IPC_RMID, 0);
  49.                     _exit(0);
  50.                 } else {
  51.                     target = ((value%nproc)*(value%nproc)*
  52.                             (value%nproc)*(value%nproc))%nproc;
  53.                     unlock.sem_num = target;
  54.                     memory[0] = target+1;
  55.                     memory[1] = value;
  56.                     memory[2] = i+1;
  57.                     semop(sem_id, &unlock, 1);
  58.                 }
  59.             }
  60.         }
  61.     }
  62.     struct sembuf unlock = {0, 1, 0};
  63.     memory[0] = 1;
  64.     memory[1] = 0;
  65.     memory[2] = 0;
  66.     semop(sem_id, &unlock, 1);
  67.     while (wait(NULL) > 0) {}
  68.     shmctl(shm_id, IPC_RMID, NULL);
  69.  
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement