Advertisement
Guest User

Untitled

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