Created
September 23, 2019 23:30
-
-
Save htfy96/4b4c38905f1dfb9ac781d8c53c6b551a to your computer and use it in GitHub Desktop.
Detecting child exit with pipe
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 <sys/types.h> | |
#include <fcntl.h> | |
#include <unistd.h> | |
#include <assert.h> | |
#include <sys/select.h> | |
#include <stdbool.h> | |
int main(void) { | |
int fds[2]; | |
assert(pipe(fds) == 0); | |
fcntl(fds[0], F_SETFD, O_CLOEXEC); | |
if (fork()) { | |
close(fds[1]); | |
fd_set fdset; | |
FD_ZERO(&fdset); | |
FD_SET(fds[0], &fdset); | |
int ret; | |
do { | |
ret = select(fds[0] + 1, &fdset, NULL, NULL, NULL); | |
printf("%d\n", ret); | |
} while (ret == 0); | |
if (ret < 0) | |
perror("select err"); | |
puts("Child exits!\n"); | |
return 0; | |
// parent | |
} else { | |
// child | |
sleep(1); | |
printf("exits"); | |
return 1; | |
} | |
assert(false && "should not reach"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment