Created
February 6, 2018 13:45
-
-
Save zduey/90e8efc5d180a53b785f9561d881c7ac to your computer and use it in GitHub Desktop.
POC: Calling fork() from a child process
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compile with: gcc -Wall -pedantic -Werror fork_from_child.c -o fork_example