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