Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
POC: Calling fork() from a child process
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
// Sample program to convince myself that you can call fork() from a child process
// Since all processes in UNIX derive from init, this seemed like it would have to
// be true, but just chekcing.
int main() {
pid_t pid_1;
pid_t pid_2;
pid_1 = fork();
if (pid_1 == -1) {
perror("fork");
exit(1);
}
else if (pid_1 == 0) {
puts("Hello from first child");
pid_2 = fork();
if (pid_2 == -1) {
perror("child fork");
exit(1);
}
else if (pid_2 == 0) {
puts("Hello from second child");
sleep(2);
exit(0);
}
else {
puts("Hello from second parent");
wait(NULL);
exit(EXIT_SUCCESS);
}
}
else {
puts("Hello from first parent");
wait(NULL);
exit(EXIT_SUCCESS);
}
return EXIT_SUCCESS;
}
@zduey

This comment has been minimized.

Copy link
Owner Author

zduey commented Feb 6, 2018

Compile with: gcc -Wall -pedantic -Werror fork_from_child.c -o fork_example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.