Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/sem.h>
- #include <stdlib.h>
- #include <sys/shm.h>
- #include <errno.h>
- #include <sys/wait.h>
- enum { BASE = 10 };
- int main(int argc, char *argv[]) {
- int nproc = strtol(argv[1], NULL, BASE);
- key_t key = ftok("/", 1);
- int semid = semget(key, nproc, 0666 | IPC_CREAT | IPC_EXCL);
- if (semid < 0) {
- _exit(errno);
- }
- pid_t p;
- int x;
- for (int i = 0; i < nproc; ++i) {
- if ((p = fork()) == -1) {
- _exit(errno);
- }
- if (!p) {
- while (semop(semid, (struct sembuf[]){{i, -1, 0}}, 1) >= 0) {
- if(scanf("%d", &x) != 1) {
- semctl(semid, 0, IPC_RMID);
- _exit(0);
- }
- printf("%d %d\n", i, x);
- fflush(stdout);
- semop(semid, (struct sembuf[]) {{x % nproc, 1, 0}}, 1);
- }
- }
- }
- if (semop(semid, (struct sembuf[]) {{0, 1, 0}}, 1) < 0) {
- _exit(errno);
- }
- for (int i = 0; i < nproc; ++i) {
- wait(NULL);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement