Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/ipc.h>
- #include <sys/sem.h>
- #include <sys/shm.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <sys/wait.h>
- /* semctl union */
- union semun
- {
- int val;
- struct semid_ds *buf;
- unsigned short *array;
- };
- void sem_wait(int semid)
- {
- struct sembuf sb = {0, -1, 0};
- semop(semid, &sb, 1);
- }
- void sem_signal(int semid)
- {
- struct sembuf sb = {0, +1, 0};
- semop(semid, &sb, 1);
- }
- int main()
- {
- key_t key = ftok(".", 75);
- /* Shared memory */
- int shmid = shmget(key, sizeof(int), 0666 | IPC_CREAT);
- int *counter = (int *)shmat(shmid, NULL, 0);
- *counter = 0;
- /* Semaphore */
- int semid = semget(key, 1, 0666 | IPC_CREAT);
- union semun arg;
- arg.val = 1; // mutex
- semctl(semid, 0, SETVAL, arg);
- pid_t pid = fork();
- if (pid == 0)
- {
- /* Child */
- for (int i = 0; i < 5; i++)
- {
- sem_wait(semid);
- (*counter)++;
- printf("Child incremented counter to %d\n", *counter);
- sem_signal(semid);
- sleep(1);
- }
- exit(0);
- }
- else if (pid > 0)
- {
- /* Parent */
- for (int i = 0; i < 5; i++)
- {
- sem_wait(semid);
- (*counter)++;
- printf("Parent incremented counter to %d\n", *counter);
- sem_signal(semid);
- sleep(1);
- }
- wait(NULL);
- /* Cleanup */
- shmdt(counter);
- shmctl(shmid, IPC_RMID, NULL);
- semctl(semid, 0, IPC_RMID);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment