I am learning about forks and processes in linux and have a question concerning the initial parent process. Is this initial parent process considered the program?
For example this code where I create 2 forks
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv, char **envp)
{
printf("%d *\n", getpid());
fork();
printf("%d *\n", getpid());
fork();
printf("%d *\n", getpid());
sleep(20);
return EXIT_SUCCESS;
}
From what I know there would be an initial parent process(which I believe is the program), and then there would be the initial fork creating a child process.
This leaves 2 processes. Then the other fork creates 2 more child processes for 5 processes total including the initial parent process.
From that understanding, the total number of child processes would be 3(2^2-1) and the total processes created besides the initial parent process would be 4.
Is my thinking correct?
Also, what would cause a fork to fail?
Not exactly, each fork()
call creates exactly one additional process. In this example You'd have a total of 4 processes, including parent process.
EDIT: I recommend reading manual for methods that You learn and use e.g. http://man7.org/linux/man-pages/man2/fork.2.html
You'll find there all the explanation, including possible failure reasons.