Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <semaphore.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <sys/shm.h>
- typedef sem_t Semaphore;
- Semaphore *sem1, *sem2;
- int main(int argc, char *argv[])
- {
- pid_t pid0;
- pid_t pid1;
- sem1 = sem_open ("Sem1", O_CREAT | O_EXCL, 0644, 1); //semaphores init
- sem2 = sem_open ("Sem2", O_CREAT | O_EXCL, 0644, 0);
- key_t shmkey;
- int shmid;
- int *x;
- shmkey = ftok ("/dev/null",5); //shared var init
- shmid = shmget(shmkey, sizeof (int),0644 | IPC_CREAT);
- if(shmid<0) //error check for the shared memory
- {
- perror("shmget\n");
- exit(1);
- }
- x = (int*) shmat(shmid,NULL,0);
- *x = 0;
- pid0 = fork();
- if (pid0 > 0) //parent
- {
- pid0 = fork();
- if(pid0>0)
- {
- sem_wait(sem2);
- sem_post(sem2);
- sem_wait(sem1);
- printf("Before process 1: %d ",*x);
- *x = *x * 2;
- printf ("after 1:%d \n",*x);
- sem_post(sem1);
- wait(NULL);
- }
- else if (pid0 == 0) //child
- {
- sem_wait(sem1);
- printf("Before process 2: %d ",*x);
- *x =*x * (* x);
- printf ("after 2:%d \n",*x);
- sem_post(sem2);
- wait(NULL);
- pid1 = fork();
- }
- else
- {
- sem_unlink("Sem1");
- sem_unlink("Sem2");
- sem_close(sem1);
- sem_close(sem2);
- printf("Fork1 failed. \n");
- }
- sem_unlink ("Sem1");
- sem_close(sem1);
- sem_unlink("Sem2");
- sem_close(sem2);
- }
- else if (pid0 == 0) //child of the child
- {
- sem_wait(sem2);
- printf("Before process 3: %d ",*x);
- *x = *x + 3;
- printf("after 3:%d \n",*x);
- sem_post(sem2);
- sem_post(sem1);
- }
- else
- {
- sem_unlink ("Sem1");
- sem_close(sem1);
- sem_unlink("Sem2");
- sem_close(sem2);
- printf ("Fork2 error.\n");
- }
- exit (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement