Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <fcntl.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 = strtol(argv[2], NULL, BASE);
- int maxval = strtol(argv[3], NULL, BASE);
- int *val;
- int shmid = shmget(key, sizeof(*mem), 0666 | IPC_CREAT | IPC_EXCL);
- if (shmid < 0) {
- _exit(errno);
- }
- val = shmat(shmid, NULL, 0);
- *val = 0;
- int semid = semget(key, nproc, 0666 | IPC_CREAT | IPC_EXCL);
- if (semid < 0) {
- _exit(errno);
- }
- pid_t p;
- 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) {
- printf("%d: %d\n", i, *val);
- if(*val == maxval) {
- semctl(semid, 0, IPC_RMID);
- shmctl(shmid, IPC_RMID, NULL);
- _exit(0);
- }
- (*val)++;
- if (semop(semid,(struct sembuf[]){{((long long)(*val) * (long long)(*val)) % nproc, 1, 0}},1) == -1) {
- _exit(errno);
- }
- }
- }
- }
- 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