/* this is an example on the use of semaphores in UNIX */ #include /* The include files necessary for using semaphores */ #include #include #include #include /* Header file needed to use waitpid system call */ #define SEM_MODE (SEM_A | SEM_R | IPC_CREAT) #define NUM_OF_SEMAPHORES 3 /* The number of semaphores that semget will create */ #define DOWN -1 /* Constant values for the semaphore operation */ #define UP 1 main() { int semid, pid; int *ptr; /* union wait status; */ int status; struct sembuf *ksems; /* System call to create an array of semaphores */ /* Unix initializes all semaphores to 0 */ if ((semid = semget(IPC_PRIVATE,NUM_OF_SEMAPHORES ,SEM_MODE)) == -1) { printf("Unsuccessful semaphore creation \n"); printf("Errno was %d \n",errno); exit(-1); } if ((pid = fork()) != 0) { /* This is the parent */ ksems = (struct sembuf *)malloc(sizeof(struct sembuf)); ksems->sem_num = 1; /* Operate on semaphore 1 */ ksems->sem_op = DOWN; printf ("Parent: I am doing a down on semaphore 1.\n\n"); /* System call to apply operations to semaphores */ if (semop(semid,ksems,1) == -1) { printf("error modifing semaphore \n"); printf("Errno was %d \n",errno); exit(-1); } printf("Parent: Ok, I can enter my critical section.\n\n"); sleep(10); /* Make believe critical section */ ksems->sem_num = 1; /* Operate on semaphore 1 */ ksems->sem_op = UP; printf ("Parent: I am doing an up on semaphore 1 to exit my\n"); printf ("Parent: critical section.\n"); /* System call to apply operations to semaphores */ if (semop(semid,ksems,1) == -1) { printf("error modifing semaphore \n"); printf("Errno was %d \n",errno); exit(-1); } waitpid(pid, &status, 0); /* Make sure that child process has completed */ /* System call to destroy semaphore array */ if (semctl(semid, IPC_RMID, 0) == -1) { printf("error destroying semaphore array.\n"); printf("Errno was %d. \n", errno); exit(-1); } } else { /* This is the child */ sleep (5); ksems = (struct sembuf *)malloc(sizeof(struct sembuf)); ksems->sem_num = 1; /* Operate on semaphore 1 */ ksems->sem_op = UP; printf ("Child: I am doing an up on semaphore 1.\n\n"); /* System call to apply operations to semaphores */ if (semop(semid,ksems,1) == -1) { printf("error modifing semaphore \n"); printf("Errno was %d \n",errno); exit(-1); } } }