Skip to content

Instantly share code, notes, and snippets.

@asmichi
Created February 2, 2019 11:21
Show Gist options
  • Save asmichi/48ff9d0497d513d298b53c30f07b83c7 to your computer and use it in GitHub Desktop.
Save asmichi/48ff9d0497d513d298b53c30f07b83c7 to your computer and use it in GitHub Desktop.
What happens when you perform waitpid(-1, ...)?
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <stdbool.h>
#include <memory.h>
void signal_handler(int sig)
{
if (sig != SIGCHLD)
{
return;
}
// Auto-reap all children.
int wstatus;
pid_t pid;
do
{
while ((pid = waitpid(-1, &wstatus, WNOHANG)) == -1 && errno == EINTR) {}
} while (pid > 0);
}
int main()
{
struct sigaction act = {0};
act.sa_handler = signal_handler;
if (sigaction(SIGCHLD, &act, NULL))
{
perror("sigaction");
return 1;
}
// This loop will intermittently print "waitpid: No child processes".
while (true)
{
// Suppose below is a code fragment deep inside a library function.
pid_t pid = fork();
if (pid == -1)
{
perror("fork");
return 1;
}
else if (pid == 0)
{
// child
_exit(1);
}
else
{
// parent
int wstatus;
pid_t ret;
while ((ret = waitpid(pid, &wstatus, 0)) == -1 && errno == EINTR) {}
if (ret == -1)
{
// Failed to obtain the exit status. Hey, it's _MY_ child! BOOOO!
perror("waitpid");
}
else
{
// Obtained the exit status. OK!
// printf("Child (PID %d) exited: status = %08x\n", wstatus);
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment