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");
pid_t fork_result = fork();
if(fork_result < 0)
{
fprintf(
stdout,
"Main process: forking failed with '%s'\n",
strerror(fork_result)
);
return fork_result;
}
if(fork_result == 0)
{
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;
}
else
{
fprintf(stdout, "Main process: successfully forked\n");
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");
int status = 0;
wait(&status);
if(WIFEXITED(status))
{
fprintf(
stdout,
"Main process: child %d exitted with code %d\n",
fork_result,
WEXITSTATUS(status)
);
}
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;
}