Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h> /* printf() */
- #include <stdlib.h> /* exit(), malloc(), free() */
- #include <sys/types.h> /* key_t, sem_t, pid_t */
- #include <sys/shm.h> /* shmat(), IPC_RMID */
- #include <errno.h> /* errno, ECHILD */
- #include <semaphore.h> /* sem_open(), sem_destroy(), sem_wait().. */
- #include <fcntl.h> /* O_CREAT, O_EXEC */
- #include <unistd.h>
- #include <sys/wait.h>
- #include <sys/shm.h>
- typedef sem_t Semaphore;
- /* semaphores are usually declared global variables */
- /* synch semaphore */
- Semaphore *LP1;
- Semaphore *LP2;
- int main ()
- {
- int i; /* loop variables */
- pid_t pid; /* fork pid */
- int child_status;
- /* Declaring Shared memory variables */
- key_t shmkey;
- int shmid;
- int *x;
- /* Initializing a shared variable in shared memory */
- shmkey = ftok ("/dev/null", 5);
- shmid = shmget(shmkey, sizeof (int), 0644 | IPC_CREAT);
- /* initialize semaphores for shared processes */
- LP1 = sem_open ("LefterisP1", O_CREAT | O_EXCL, 0644, 0/*Initial value */);
- LP2 = sem_open ("LefterisP2", O_CREAT | O_EXCL, 0644, 0/*Initial value */);
- /* fork child processes */
- for (i=0; i<1; i++)
- {
- pid = fork ();
- if (pid == 0)
- {
- break;
- }
- }
- /* 1st child */
- if (pid == 0)
- {
- sem_wait(LP2);
- printf("I timi tou x prin tin diergasia 1: %d\n", *x);
- *x = *x * 2;
- printf("I timi tou x meta tin diergasia 1: %d\n", *x);
- wait(NULL);
- }
- /* 2nd child */
- else if (pid != 0 && pid == 0)
- {
- printf("I timi tou x prin tin diergasia 2: %d\n", *x);
- *x = *x * (*x);
- printf("I timi tou x meta tin diergasia 2:%d\n", *x);
- sem_post(LP1);
- wait(NULL);
- }
- else
- {
- sem_wait(LP1);
- printf("I timi prin tin diergasia 3:%d\n", *x);
- *x = *x + 3;
- printf("I timi meta tin diergasia 3:%d\n", *x);
- sem_post(LP2);
- printf(" Parent unlinks the semaphores\n Bye\n");
- /* unlink prevents the semaphore existing forever */
- /* if a crash occurs during the execution */
- sem_unlink ("LefterisP1");
- sem_close(LP1);
- sem_unlink ("LefterisP2");
- sem_close(LP2);
- }
- exit (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement