Advertisement
Guest User

Untitled

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