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_id, sem_id;
- if ((shm_id = shmget(key, 3 * sizeof(int), IPC_CREAT | 0600)) == -1) {
- return 1;
- }
- int *memory = shmat(shm_id, 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 = {i, -1, 0};
- struct sembuf unlock = {-1, 1, 0};
- printf("jopa\n");
- fflush(stdout);
- while (1) {
- if (semop(sem_id, &lock, 1) == -1) {
- _exit(0);
- }
- printf("cock");
- fflush(stdout);
- value = memory[1];
- value++;
- printf("%d %d %d\n", memory[0], memory[1], memory[2]);
- fflush(stdout);
- if (value > maxval) {
- semctl(sem_id, 1, IPC_RMID, 0);
- _exit(0);
- } else {
- target = ((value%nproc)*(value%nproc)*
- (value%nproc)*(value%nproc))%nproc + 1;
- unlock.sem_num = target;
- memory[0] = target;
- memory[1] = value;
- memory[2] = i+1;
- semop(sem_id, &unlock, 1);
- }
- }
- }
- }
- struct sembuf unlock = {0, 1, 0};
- memory[0] = 1;
- memory[1] = 0;
- memory[2] = 0;
- semop(sem_id, &unlock, 1);
- while (wait(NULL) > 0) {}
- shmctl(shm_id, IPC_RMID, NULL);
- return 0;
- }
Add Comment
Please, Sign In to add comment