Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <inttypes.h>
- #include <sys/sem.h>
- #include <sys/shm.h>
- #include <sys/ipc.h>
- #include <unistd.h>
- #include <stdio.h>
- enum { DECIMAL_BASE = 10 };
- int
- main(int argc, char *argv[])
- {
- pid_t pid;
- int nproc = strtol(argv[1], NULL, DECIMAL_BASE);
- int key = strtol(argv[2], NULL, DECIMAL_BASE);
- int maxval = strtoull(argv[3], NULL, DECIMAL_BASE);
- int shm_key, sem_id;
- if ((shm_key = shmget(key, 3 * sizeof(int), IPC_CREAT | 0600)) == -1) {
- return 1;
- }
- int *memory = shmat(shm_key, NULL, 0);
- if (memory == NULL) {
- return 1;
- }
- if ((sem_id = semget(key, nproc, IPC_CREAT | 0600)) == -1) {
- return 1;
- }
- for (int i = 0; i < nproc; ++i) {
- if (semctl(sem_id, i, SETVAL, 0) == -1) {
- return 1;
- }
- }
- for (int i = 0; i < nproc; ++i) {
- pid = fork();
- if (pid == -1) {
- return 1;
- } else if (!pid) {
- int value, target;
- struct sembuf lock = {-1, -1, 0};
- struct sembuf unlock = {-1, 1, 0};
- while (1) {
- while(semop(sem_id, ))
- }
- }
- }
- memory[0] = 1;
- memory[1] = 0;
- memory[2] = 0;
- while (wait(NULL) > 0) {}
- if (semctl(sem_id, 1, IPC_RMID, 0) == -1) {
- return 1;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement