ch3-SIGCHLD

Chapter_3     zombie Chapter_4







sigchld.c     ALP, p. 61-62


#include <stdio.h> // for printf(), NULL
#include <stdlib.h> // for exit()
#include <signal.h> // for sigaction()
// signal.h includes bits/types/sig_atomic_t.h, which defines sig_atomic_t
// signal.h includes bits/sigaction.h, which defines struct sigaction
// signal.h includes bits/signum.h, which defines SIGCHLD:
// /usr/include/x86_64-linux-gnu/bits/signum.h:
// #define SIGCHLD 17
#include <string.h> // for memset()
#include <sys/types.h> // for pid_t
#include <sys/wait.h> // for wait()
#include <unistd.h> // for fork(), sleep()

sig_atomic_t child_exit_status;

void clean_up_child_process (int signal_number)
{
int status;
wait (&status);
/* Store its exit status in a global variable: */
child_exit_status = status;
printf("Signal number: %d\n", signal_number);
}

int main()
{
/* Handle SIGCHLD by calling clean_up_child_process() */
struct sigaction sigchld_action;
memset (&sigchld_action, 0, sizeof(sigchld_action));
sigchld_action.sa_handler = &clean_up_child_process;
sigaction (SIGCHLD, &sigchld_action, NULL);

printf("SIGCHLD = %d\n", SIGCHLD);

int awake;
pid_t childid;
childid = fork(); // fork a child process

if (childid > 0) // parent process
{
printf("Child pid: %d\n", childid);
awake = sleep(10); // wait for child to finish,
printf("Awake: %d\n", awake); // sleep interrupted by signal
printf("Child exit status: %d\n", child_exit_status);
}
else // child process
{exit(0);} // exit immediately

return 0; // parent process
}

/*
gcc sigchld.c -o sigchld
./sigchld
SIGCHLD = 17
Child pid: 60301
Signal number: 17
Awake: 9
Child exit status: 0
*/









Chapter_3     zombie BACK_TO_TOP Chapter_4



Comments

Popular posts from this blog

Contents