Skip to content

Instantly share code, notes, and snippets.

@DocBohn
Last active March 16, 2025 18:19
Show Gist options
  • Save DocBohn/3f1a419b9c8a2cbd8ed9b68f8f190f1a to your computer and use it in GitHub Desktop.
Save DocBohn/3f1a419b9c8a2cbd8ed9b68f8f190f1a to your computer and use it in GitHub Desktop.
Demonstration of creating new processes and waiting for them to terminate
#include <stdio.h>
#include <unistd.h>
void fork_demo() {
pid_t pid;
printf("Before fork. \tme =%8d\tchild = n/a\tparent = %8d\n", getpid(), getppid());
pid = fork();
printf("After fork. \tme =%8d\tchild =%8d\tparent = %8d\n", getpid(), pid, getppid());
pid = fork();
printf("Another fork.\tme =%8d\tchild =%8d\tparent = %8d\n", getpid(), pid, getppid());
}
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdlib.h>
static void reap_children();
static void sleep_and_exit(int exit_value);
void wait_demo() {
if (fork()) { // the parent process
if (fork()) {
reap_children();
} else {
sleep_and_exit(1);
}
} else { // the child process
sleep_and_exit(0);
}
}
static void reap_children() {
pid_t pid;
int status;
while ((pid = wait(&status)) > 0) {
if (WIFEXITED(status)) {
printf("Process %d terminated with exit status %d.\n", pid, WEXITSTATUS(status));
} else {
printf("Process %d terminated abnormally.\n", pid);
}
}
if (errno == ECHILD) {
printf("No more children.\n");
} else {
printf("Unexpected error returned by wait().\n");
}
}
static void sleep_and_exit(int exit_value) {
sleep(1);
exit(exit_value);
}
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
static void sleep_and_exit(int exit_value);
void waitpid_demo() {
bool is_parent = true;
int number_of_children = 4;
int status;
pid_t pid, pids[number_of_children];
for (int i = 0; i < number_of_children; i++) {
pid = fork();
if (pid == 0) {
is_parent = false;
} else {
pids[i] = pid;
}
}
if (!is_parent) {
sleep_and_exit(0);
} else {
long counter = 1;
while ((pid = waitpid(pids[0], &status, WNOHANG)) == 0) {
counter++;
}
printf("Process %d terminated after %ld calls to waitpid().\n", pid, counter);
pid = waitpid(pids[1], &status, 0);
printf("Process %d terminated.\n", pid);
counter = 1;
while ((pid = waitpid(-1, &status, WNOHANG)) == 0) {
counter++;
}
printf("Process %d terminated after %ld calls to waitpid().\n", pid, counter);
pid = waitpid(-1, &status, 0);
printf("Process %d terminated.\n", pid);
}
}
static void sleep_and_exit(int exit_value) {
sleep(1);
exit(exit_value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment