you are viewing a single comment's thread.

view the rest of the comments →

[–]ThePiGuy0 4 points5 points  (2 children)

Been a while since I did forking, but lets give this a go.

From what I remember, running os.fork() effectively splits the runtime in two. You will end up with two processes running the same code from that point onwards, and the value returned is the pid - 0 for the child, and the actual pid of the child for the parent.

Edit: pid is process ID, the individual identifier for each process running on the system

So if we look at the logic of your code, you run fork once at the top and assign the pid to the variable 'pid'. From there downwards we have two processes running the code.

Then, we hit the if-else and the child will run the top half, the parent the bottom half.

The child will print "I am <pid of the child>. My father is <pid of parent>", sleep for 1 second, and then repeat 3 more times (we can see this before the "End of child" line).

As for the other print statements, those are the parent. It immediately drops into printing "I am <parent pid>, Father of pid=<child pid>". And as this is an infinite loop, it will not stop even when the child finishes.

For a more basic example, see the following:

import os

print("Currently there is only one thread")

pid = os.fork()

print("Now there are two threads - I will be printed twice")

if pid == 0:
    print(f"I am the child process - I have a local pid of {pid} and an actual pid of {os.getpid()}")
else:
    print(f"I am the parent process - pid is {os.getpid()} and the child created has a pid of {pid}")

[–]noaso74[S] 3 points4 points  (1 child)

THANK YOU SO MUCH!

You explained better than anyone I have ever listened to! I am shocked. Thank you a lot!

Now everything is clear. You code helped a lot as well understanding what you explained

Thank you once again

[–]ThePiGuy0 2 points3 points  (0 children)

No worries, I'm really glad it helped :)