wowonline

Untitled

Dec 15th, 2021
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.24 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(int), 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.     for (int i = 0; i < nproc; ++i) {
  31.         if (semctl(sem_id, i, SETVAL, 0) == -1) {
  32.             return 1;
  33.         }
  34.     }
  35.  
  36.     for (int i = 0; i < nproc; ++i) {
  37.         pid = fork();
  38.         if (pid == -1) {
  39.             return 1;
  40.         } else if (!pid) {
  41.             int value, target;
  42.             struct sembuf lock = {i, -1, 0};
  43.             struct sembuf unlock = {-1, 1, 0};
  44.             printf("jopa\n");
  45.             fflush(stdout);
  46.             while (1) {
  47.                 if (semop(sem_id, &lock, 1) == -1) {
  48.                     _exit(0);
  49.                 }
  50.                 printf("cock");
  51.                 fflush(stdout);
  52.                 value = memory[1];
  53.                 value++;
  54.                 printf("%d %d %d\n", memory[0], memory[1], memory[2]);
  55.                 fflush(stdout);
  56.                 if (value > maxval) {
  57.                     semctl(sem_id, 1, IPC_RMID, 0);
  58.                     _exit(0);
  59.                 } else {
  60.                     target = ((value%nproc)*(value%nproc)*
  61.                             (value%nproc)*(value%nproc))%nproc + 1;
  62.                     unlock.sem_num = target;
  63.                     memory[0] = target;
  64.                     memory[1] = value;
  65.                     memory[2] = i+1;
  66.                     semop(sem_id, &unlock, 1);
  67.                 }
  68.             }
  69.         }
  70.     }
  71.     struct sembuf unlock = {0, 1, 0};
  72.     memory[0] = 1;
  73.     memory[1] = 0;
  74.     memory[2] = 0;
  75.     semop(sem_id, &unlock, 1);
  76.     while (wait(NULL) > 0) {}
  77.     shmctl(shm_id, IPC_RMID, NULL);
  78.  
  79.     return 0;
  80. }
Add Comment
Please, Sign In to add comment