Skip to content

Instantly share code, notes, and snippets.

@Alexey-N-Chernyshov
Last active May 26, 2016 08:50
Show Gist options
  • Save Alexey-N-Chernyshov/4031630 to your computer and use it in GitHub Desktop.
Save Alexey-N-Chernyshov/4031630 to your computer and use it in GitHub Desktop.
Get zombie exec status.
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
// SIGCHLD handler
void bury_zombies(int sig_number)
{
pid_t zombie_pid;
int stat_loc;
if (sig_number == SIGCHLD) {
printf("SIGCHLD handler\n");
// More then one SIGCHLD signal can be sent from multiple zombie processes,
// but we get only one signal. So, wait() for all finished child processes.
while ((zombie_pid = wait(&stat_loc)) > 0)
// Use WEXITSTATUS() macro to get exit status.
printf("Wait() for zombie with pid %d, its exec code %d.\n", zombie_pid, WEXITSTATUS(stat_loc));
}
}
int main()
{
int i;
struct sigaction sa;
// Set up the signal handler.
sa.sa_handler = bury_zombies;
if (sigaction(SIGCHLD, &sa, 0)) {
perror ("sigaction() error");
return EXIT_FAILURE;
}
// Spawn 10 childs that return "i".
int res;
for (i = 0; i < 10; ++i) {
res = fork();
if (res == 0) {
// inside the child
printf("Child pid is %d\n", getpid());
return i;
} else if (res < 0 ) {
perror("fork() error");
return EXIT_FAILURE;
}
}
printf("Parent pid is %d\n", getpid());
getchar();
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment