Skip to content

Instantly share code, notes, and snippets.

@h4k1m0u
Created May 11, 2022 19:39
Show Gist options
  • Save h4k1m0u/d774bad8a92dfaf7722d90be07b98b82 to your computer and use it in GitHub Desktop.
Save h4k1m0u/d774bad8a92dfaf7722d90be07b98b82 to your computer and use it in GitHub Desktop.
Fork children processes & wait for them to finish
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
const int n_processes = 5;
pid_t pid;
// spawn n processes
for (size_t i = 0; i < n_processes; ++i) {
pid = fork();
if (pid == 0) { // in child
printf("Spawning process %d\n", getpid());
exit(EXIT_SUCCESS);
}
else if (pid > 0) { // in parent
printf("From parent: created child pid %d\n", pid);
}
}
// parent waits for each child process to terminate
// otherwise, exiting children become zombie processes (& won't notify their parent of their exit)
while ((pid = wait(NULL)) != -1) {
printf("Terminating process %d\n", pid);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment