Last active
January 20, 2019 14:17
-
-
Save croepha/e699f662ce3bc4907929c2a6900ec55e 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 <pthread.h> | |
#include <errno.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <assert.h> | |
#include <sys/stat.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
void*thread1(void*) { | |
auto p1 = fork(); | |
assert(p1!=-1); | |
if (!p1) { | |
sleep(4); | |
exit(0); | |
} | |
auto p2 = fork(); | |
assert(p2!=-1); | |
if (!p2) { | |
sleep(4); | |
exit(0); | |
} | |
printf("p1 %d\n", p1); | |
printf("p2 %d\n", p2); | |
// wait for either p1 or p2 | |
while (p1 != -1 || p2 != -1) { | |
#if 1 | |
siginfo_t w1; | |
auto r1 = waitid(P_ALL, -1, &w1, WEXITED|WNOWAIT); | |
printf("W1 %d %d %d %s\n", r1, w1.si_pid, w1.si_status, strerror(errno)); | |
if (r1 != -1 && w1.si_pid == p1) { | |
int w2; | |
auto r2 = waitpid(p1, &w2, 0); | |
printf("W2 %d %d %s\n", r2, w2, strerror(errno)); | |
assert(r2 == p1); | |
p1 = -1; | |
}; | |
if (r1 != -1 && w1.si_pid == p2) { | |
int w2; | |
auto r2 = waitpid(p2, &w2, 0); | |
printf("W2 %d %d %s\n", r2, w2, strerror(errno)); | |
assert(r2 == p2); | |
p2 = -1; | |
}; | |
#else | |
int w1; | |
auto r1 = wait(&w1); | |
printf("W %d %d %s\n", r1, w1, strerror(errno)); | |
if (r1 != -1 && r1 == p1) p1 = -1; | |
if (r1 != -1 && r1 == p2) p2 = -1; | |
#endif | |
} | |
printf("W\n"); | |
return 0; | |
} | |
void thread2() { | |
sleep(1); | |
auto r1 = system("sleep 1"); | |
printf("S1 %d\n", r1); | |
auto r2 = system("sleep 1"); | |
printf("S2 %d\n", r2); | |
} | |
int main () { | |
pthread_t thread1_h; | |
pthread_create(&thread1_h, 0, thread1, 0); | |
thread2(); | |
pthread_join(thread1_h, 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment