Shows process forking and signalling
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
void handle_signal(int signum)
{
const char* signame = "UNKNOWN";
if(signum == SIGTERM) signame = "TERM";
if(signum == SIGCHLD) signame = "CHLD";
printf("Process %d received signal '%s'\n", getpid(), signame);
}
int main(int argc, const char* argv[])
{
srand(getpid());
printf("Main process %d started\n", getpid());
signal(SIGTERM, handle_signal);
signal(SIGCHLD, handle_signal);
pid_t fork_result = fork();
if(fork_result < 0)
{
perror("Fork failed");
return fork_result;
}
if(fork_result == 0)
{
sleep(3);
return 0;
}
else
{
sleep(1);
if(rand() % 2 == 0)
kill(fork_result, SIGTERM);
else kill(fork_result, SIGINT);
int status = 0;
wait(&status);
if(WIFEXITED(status))
printf("Child %d exitted with code %d\n", fork_result, WEXITSTATUS(status));
if(WIFSIGNALED(status))
printf("Child %d terminated by signal %d\n", fork_result, WTERMSIG(status));
}
return 0;
}