Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/wait.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #include <sys/sem.h>
- enum { BASE = 10 };
- int main(int argc, char *argv[])
- {
- int n = (int) strtol(argv[1], NULL, BASE);
- key_t key = (int) strtol(argv[2], NULL, BASE);
- unsigned long long maxval = (int)strtol(argv[3], NULL, BASE);
- //int n = 2;
- //key_t key = 12;
- //unsigned long long maxval = 4;
- int sem_id = semget(key, n, 0666 | IPC_CREAT | IPC_EXCL);
- if (sem_id < 0) {
- //exit(1);
- }
- int shm_id = shmget(key, 2 * sizeof(int), 0666 | IPC_CREAT | IPC_EXCL);
- if (shm_id < 0) {
- //exit(1);
- }
- int *shmaddr = (int*) shmat(shm_id, NULL, 0);
- shmaddr[0] = 0;
- shmaddr[1] = 0;
- for (int i = 0; i < n; i++) {
- pid_t pid = fork();
- if (pid == 0) {
- while (semop(sem_id, (struct sembuf[]){{i, -1, 0}}, 1) >= 0) {
- printf("%d %d %d\n", i + 1, shmaddr[0], shmaddr[1]);
- fflush(stdout);
- if(shmaddr[0] >= maxval) {
- semctl(sem_id, 0, IPC_RMID);
- //shmctl(shm_id, IPC_RMID, NULL);
- //exit(0);
- }
- shmaddr[0]++;
- shmaddr[1] = i + 1;
- int tmp = (((shmaddr[0] % n) * (shmaddr[0] % n)) % n * ((shmaddr[0] % n) * (shmaddr[0] % n)) % n) % n;
- if (semop(sem_id,(struct sembuf[]){{tmp, 1, 0}},1) < 0) {
- //exit(1);
- }
- }
- } else if (pid < 0) {
- exit(1);
- }
- }
- if (semop(sem_id, (struct sembuf[]) {{0, 1, 0}}, 1) < 0) {
- //exit(1);
- }
- while (wait(NULL) > 0) {
- }
- //shmdt(shmaddr);
- if (semctl(sem_id, 0, IPC_RMID) < 0) {
- //exit(1);
- }
- if (shmctl(shm_id, 0, IPC_RMID) < 0) {
- //exit(1);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement