Created
September 11, 2017 13:41
-
-
Save disconnect3d/0b76c38133d7ccebd7d1c86cdc502797 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <semaphore.h> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#define INFOFUNC printf("[%d] %s\n", getpid(), __FUNCTION__) | |
#define INFO(m) printf("[%d] %s\n", getpid(), m) | |
sem_t* parent_sem; | |
sem_t* sem; | |
void process1_launch() { | |
INFOFUNC; | |
INFO("Waiting for proc2"); | |
sem_wait(sem); // wait for process 2 | |
INFO("Released proc2"); | |
INFO("Sending post to parent"); | |
sem_post(parent_sem); | |
INFO("Post to parent sent"); | |
} | |
void process2_launch() { | |
INFOFUNC; | |
INFO("Proc2 sleep"); | |
sleep(3); | |
INFO("Proc2 wake up"); | |
sem_post(sem); | |
INFO("Released semafore"); | |
} | |
#define SEMNAME1 "/sem1111" | |
#define SEMNAME2 "/sem2222" | |
int main() { | |
// create semaphore | |
sem = sem_open(SEMNAME1, O_CREAT | O_EXCL, 0644, 0); | |
sem_unlink(SEMNAME1); | |
parent_sem = sem_open(SEMNAME2, O_CREAT | O_EXCL, 0644, 0); | |
sem_unlink(SEMNAME2); | |
printf("parent, sem=%p, parent_sem=%p\n", sem, parent_sem); | |
pid_t f1 = fork(); | |
if (f1 == 0) { | |
printf("child1, sem=%p, parent_sem=%p\n", sem, parent_sem); | |
process1_launch(); | |
INFO("ending"); | |
return 0; // child dont go further | |
} | |
pid_t f2 = fork(); | |
if (f2 == 0) { | |
printf("child2, sem=%p, parent_sem=%p\n", sem, parent_sem); | |
process2_launch(); | |
INFO("ending"); | |
return 0; // child dont go furter | |
} | |
// parent wait for proc1 end | |
INFO("Parent wait"); | |
sem_wait(parent_sem); | |
INFO("Parent ending"); | |
printf("parent, sem=%p, parent_sem=%p\n", sem, parent_sem); | |
printf("close sem=%d\n", sem_close(sem)); | |
printf("close parentsem=%d\n", sem_close(parent_sem)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment