Child Process using fork() method in Python
In this tutorial, we will see what is fork() method in Python and how it works with the Child Process with few examples. It is a famous concept and many times you must have heard about it.
Here we will understand the whole concept from scratch and learn how it is one of the most important concepts Object-Oriented Programming.
So let’s get started.
Child Process using fork()
In Python, we have something known as Child Process. Now, what it is? Child Process is a process that contains complete data as that of the Parent Process which is the main process. The Child Process is just a copy of the Parent process. It copies local variables of Parent Process and any changes done in the Parent Process do not appear in the Child Process. Each process runs until it finishes and then exit. Thus, we see that the Child Process is independent of the Parent Process.
Basically, we create a child process using the fork method. Fork creates a child process by calling the Parent process. Mainly, fork creates a separate and special place for the child process. It is possible for the parent process to have many child processes. Therefore, every child process has been assigned with a special Process Identifier to distinguish it.
Fork returns a value always. With this value, we can decide which process we are presently dealing with. If the value is 0, then we infer that we are in the Child Process. When any positive value is returned, we infer that we are in the Parent Process. But if the returned value is any negative value then it means some problem is there and we would get some error message.
Fork in Python
In Python3, we have great importance for Fork. We need to import the OS module in Python to fork the processes. It is highly useful in multi-threading tasks where many processes are going on in parallel. It has no arguments but returns the process id.
import os def parentchild(): n = os.fork()
We have imported the os and written the definition. This is the basic step of this program.
import os pid = os.fork() if pid > 0 : print("It is a Parent process:") print("Process ID:", os.getpid()) print("Child process ID:", pid) else : print("\nIt is a Child process:") print("Id of Process:", os.getpid()) print("Parent process ID:", os.getppid())
Here we have used a special function- getpid() which returns the process id.
Similarly, os.exit is important so that the child process does not go back to the parent process and hence it ends.
The Output of the code:
Id of Process: 1088 Parent Process Id: 1087
Output can vary here. This was the simplest way to write the code for a Child Process using the Fork() method. It is a very common and useful method and you can also write it easily using Python.