Skip to content

Instantly share code, notes, and snippets.

@htfy96
Created September 23, 2019 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save htfy96/4b4c38905f1dfb9ac781d8c53c6b551a to your computer and use it in GitHub Desktop.
Save htfy96/4b4c38905f1dfb9ac781d8c53c6b551a to your computer and use it in GitHub Desktop.
Detecting child exit with pipe
#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