Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <time.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <sys/ipc.h>
- #include <sys/msg.h>
- #include <sys/shm.h>
- #include <sys/sem.h>
- #define u unsigned
- int semid, maxval, nproc;
- int* memory;
- int proc(int i){
- while (semop(semid, (struct sembuf[]){{i, -1, 0}}, 1) >= 0){
- int a = memory[0];
- printf("%d: %d\n", i, a);
- fflush(stdout);
- a++;
- if (a > maxval){
- semctl(semid, 0, IPC_RMID, (int) 0);
- return 0;
- }
- memory[0] = a;
- int next = (a * a) % nproc;
- semop(semid, (struct sembuf[]){{next, 1, 0}}, 1);
- }
- return 0;
- }
- int main(int argc, char** argv){
- nproc = strtol(argv[1], NULL, 10);
- key_t key = strtol(argv[2], NULL, 10);
- maxval = strtol(argv[3], NULL, 10);
- int shmid = shmget(key, sizeof(int), 0600 | IPC_CREAT);
- memory = shmat(shmid, NULL, 0);
- memory[0] = 0;
- semid = semget(key, nproc, 0600 | IPC_CREAT);
- semctl(semid, nproc, SETALL, (int) 0);
- struct sembuf cmd[] = {{0, 1, 0}};
- semop(semid, (struct sembuf[]){{0, 1, 0}}, 1);
- for (int i = 0; i < nproc; ++i){
- if (!fork()){
- proc(i);
- exit(0);
- }
- }
- while (wait(NULL) != -1);
- shmctl(shmid, IPC_RMID, NULL);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement