Advertisement
wowonline

Untitled

Dec 15th, 2021
859
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.37 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. enum { DECIMAL_BASE = 10 };
  10.  
  11. int
  12. main(int argc, char *argv[])
  13. {
  14.     pid_t pid;
  15.     int nproc = strtol(argv[1], NULL, DECIMAL_BASE);
  16.     int key = strtol(argv[2], NULL, DECIMAL_BASE);
  17.     int maxval = strtoull(argv[3], NULL, DECIMAL_BASE);
  18.     int shm_key, sem_id;
  19.     if ((shm_key = shmget(key, 3 * sizeof(int), IPC_CREAT | 0600)) == -1) {
  20.         return 1;
  21.     }
  22.     int *memory = shmat(shm_key, NULL, 0);
  23.     if (memory == NULL) {
  24.         return 1;
  25.     }
  26.     if ((sem_id = semget(key, nproc, IPC_CREAT | 0600)) == -1) {
  27.         return 1;
  28.     }
  29.     for (int i = 0; i < nproc; ++i) {
  30.         if (semctl(sem_id, i, SETVAL, 0) == -1) {
  31.             return 1;
  32.         }
  33.     }
  34.  
  35.     for (int i = 0; i < nproc; ++i) {
  36.         pid = fork();
  37.         if (pid == -1) {
  38.             return 1;
  39.         } else if (!pid) {
  40.             int value, target;
  41.             struct sembuf lock = {-1, -1, 0};
  42.             struct sembuf unlock = {-1, 1, 0};
  43.             while (1) {
  44.                 while(semop(sem_id, ))
  45.             }
  46.  
  47.         }
  48.     }
  49.  
  50.     memory[0] = 1;
  51.     memory[1] = 0;
  52.     memory[2] = 0;
  53.     while (wait(NULL) > 0) {}
  54.     if (semctl(sem_id, 1, IPC_RMID, 0) == -1) {
  55.         return 1;
  56.     }
  57.  
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement