Note that other than threads , fork()
creates a completely independent process. For the OS, there are two executables running in parallel, not two processes of the same executable.
The confusing part of fork()
(and key to understanding that it is not a thread substitute) is that it duplicates the process at runtime , and in full .
It does not run a new start instance , it duplicates the process even at the point where it is being processed, with all values and variables intact.
Just because of this, I think the name "parent" and "child" are not suitable, because they are perfect clones.
In particular, in this section:
def pai():
while True:
newpid = os.fork()# fornece ID para um novo processo!
#NESTE MOMENTO TEM 2 CÒDIGOS EM EXECUÇÃO NESTE MESMO PONTO
And then, each of the two running will fall from one side of the IF:
if newpid == 0 # Zero significa que é a cópia
filho()
else: # Diferente de zero é o original, cujo
# newpid é o ID do outro processo (o novo)
As we have the program duplicated and running at the same point, the only way to know which is which is by the different value returned in newpid in each case.
The best way to understand fork is to watch the movie "THE PRESTIGE", which in Brazil came as "THE GREAT TRICK":
Trailer: link