Created
May 28, 2013 21:25
-
-
Save juliushaertl/5666283 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/types.h> | |
#include <sys/ipc.h> | |
#include <sys/sem.h> | |
#define DEBUG 1 | |
static int semID; | |
void sem_wait(int); | |
void sem_signal(int); | |
int main(int argc, char** argv) { | |
semID = semget(2401, 1, 0777 | IPC_CREAT); | |
if (semID >= 0) { | |
semctl (semID, 0, SETVAL, (int) 1); | |
printf("set %d semaphore to 1\n", semID); | |
} else { | |
perror("semget"); | |
} | |
int cpid = fork(); | |
if(cpid == 0) { | |
sem_wait(semID); | |
printf("Lock from child for 5 secounds\n"); | |
sleep(5); | |
printf("Child done\n"); | |
sem_signal(semID); | |
} else { | |
sleep(1); | |
sem_wait(semID); | |
printf("Lock from parent for 2 secounds\n"); | |
sleep(2); | |
printf("Parent done\n"); | |
sem_signal(semID); | |
wait(NULL); | |
semctl (semID, 0, IPC_RMID, 0); | |
} | |
} | |
/* Wait operation on semaphore id | |
* decrement semaphore | |
*/ | |
void sem_wait(int sem_id) { | |
#if DEBUG | |
printf("Semaphore WAIT %d\n", sem_id); | |
#endif | |
struct sembuf op_wait = { | |
.sem_op = -1, | |
.sem_flg = SEM_UNDO, | |
.sem_num = 0 | |
}; | |
if( semop (sem_id, &op_wait, 1) == -1) { | |
perror(" semop failure "); | |
exit (EXIT_FAILURE); | |
} | |
} | |
/* Signal operation on semaphore id | |
* increment semaphore | |
*/ | |
void sem_signal(int sem_id) { | |
#if DEBUG | |
printf("Semaphore SIGNAL %d\n", sem_id); | |
#endif | |
struct sembuf op_signal = { | |
.sem_op = 1, | |
.sem_flg = SEM_UNDO, | |
.sem_num = 0 | |
}; | |
if( semop (sem_id, &op_signal, 1) == -1) { | |
perror(" semop failure "); | |
exit (EXIT_FAILURE); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment