Question:
I have this short code example, we were given it to demonstrate how the fork() function works:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main () {
pid_t pid;
pid = fork();
pid = fork();
printf("Fork-Test\n");
return EXIT_SUCCESS;
}
I don't quite understand the result. As a result, I write Fork-Test 4 times in the terminal. I don’t understand, firstly, why this happens more than once, because I call the printf("Fork-Test\n");
only once, secondly, times already several times, then why exactly 4? Moreover, in the following form:
Fork-Test
Fork-Test
Process returned 0 (0x0) execution time : 0.007 s
Press ENTER to continue
Fork-Test
Fork-Test
the meaning is not clear to me. I would appreciate any clarification about fork()
Answer:
The difficulty in understanding fork
is that all the processes you run are dealing with the same code you wrote.
When you called fork
the first time
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main () {
pid_t pid;
pid = fork();
// после первого вызова fork
pid = fork();
printf("Fork-Test\n");
return EXIT_SUCCESS;
}
That part of your program, which is located after the comment, is already being executed by two processes. True, each of the processes has its own address space. You can represent it like this
Родительский процесс Дочерний процесс
==================== ================
pid = fork(); pid = fork();
printf("Fork-Test\n"); printf("Fork-Test\n");
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
Now each of the processes encounters the next fork
in its path. So there are two more processes. And all four processes execute sentences in their address space
printf("Fork-Test\n");
return EXIT_SUCCESS;
}
The documentation in the fork
description says
fork() creates a new process by duplicating the calling process. The
new process is referred to as the child process. The calling process
is referred to as the parent process.
The child process and the parent process run in separate memory
spaces. **At the time of fork() both memory spaces have the same
content.**
Pay attention to the last sentence of the quote. This means that each process has, roughly speaking, the same source code for your program, which begins execution for the new process after the fork
clause.