Advertisement
Guest User

Untitled

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