FRI-OS
example/posix/processes-signals.c

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>
// A function that gets called if it is
// installed as a handler for a signal and
// that signal is recieved by the process
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());
// install the sighandler
signal(SIGTERM, handle_signal);
signal(SIGCHLD, handle_signal);
// try to fork the process
pid_t fork_result = fork();
// if that failed
if(fork_result < 0)
{
// complain and exit
perror("Fork failed");
return fork_result;
}
// if we are here and fork_result is 0 then we are
// in the child process
if(fork_result == 0)
{
// pretend doing some "work"
sleep(3);
return 0;
}
// otherwise this is executing in the parent process
else
{
// wait for a while
sleep(1);
// and then send the TERM signal to the child
if(rand() % 2 == 0)
kill(fork_result, SIGTERM);
else kill(fork_result, SIGINT);
int status = 0;
wait(&status);
// if the process exitted normally
if(WIFEXITED(status))
printf("Child %d exitted with code %d\n", fork_result, WEXITSTATUS(status));
// if the process was terminated by a signal
if(WIFSIGNALED(status))
printf("Child %d terminated by signal %d\n", fork_result, WTERMSIG(status));
}
return 0;
}