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

Shows how to fork and wait for a child process

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, const char* argv[])
{
srand(getpid());
fprintf(stdout, "Main process: forking\n");
// try to fork the process
pid_t fork_result = fork();
// if that failed
if(fork_result < 0)
{
// complain and exit
fprintf(
stdout,
"Main process: forking failed with '%s'\n",
strerror(fork_result)
);
return fork_result;
}
// if we are here and fork_result is 0 then we are
// in the child process
if(fork_result == 0)
{
// do some "work"
fprintf(stderr, "Child process %d: started\n", getpid());
sleep(2);
int child_result = rand() % 256;
fprintf(
stderr,
"Child process %d: quitting with exit code %d\n",
getpid(),
child_result
);
return child_result;
}
// otherwise this is executing in the parent process
else
{
fprintf(stdout, "Main process: successfully forked\n");
// randomly either send a signal to the process
// or let it finish normally
if(rand() % 2 == 0)
{
sleep(1);
fprintf(stdout, "Main process: signaling the child\n");
if(rand() % 2 == 0)
kill(fork_result, SIGTERM);
else
kill(fork_result, SIGINT);
}
fprintf(stdout, "Main process: waiting for child\n");
// wait for the child process to finish
// get the exit status and examine it
int status = 0;
wait(&status);
// if the process exitted normally
if(WIFEXITED(status))
{
fprintf(
stdout,
"Main process: child %d exitted with code %d\n",
fork_result,
WEXITSTATUS(status)
);
}
// if the process was terminated by a signal
if(WIFSIGNALED(status))
{
fprintf(
stdout,
"Main process: child %d terminated by signal %d\n",
fork_result,
WTERMSIG(status)
);
}
}
fprintf(stdout, "Main process: quitting\n");
return 0;
}