Skip to content

Instantly share code, notes, and snippets.

@zduey
Created February 6, 2018 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zduey/90e8efc5d180a53b785f9561d881c7ac to your computer and use it in GitHub Desktop.
Save zduey/90e8efc5d180a53b785f9561d881c7ac to your computer and use it in GitHub Desktop.
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
Copy link
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