python fork error 1

python fork error

import os

def _fork():
   raise OSError()
os.fork = _fork

for i in range(1,4):
    try:
         pid = os.fork()
    except OSError:
         print ("Error forking process")
         continue
    if pid == 0:
         print "In child process"
         os._exit(0)
    print "In parent process"

Here is what the above code is Doing:
1. We are creating a function called _fork() which raises an OSError.
2. We are assigning this function to the os.fork() function.
3. We are creating a for loop which will run 3 times.
4. Inside the for loop, we are trying to fork a process.
5. If the fork is successful, we are printing a message and exiting the child process.
6. If the fork is unsuccessful, we are printing a message and continuing with the for loop.
7. We are printing a message in the parent process.

Here’s the output of the above code:

In parent process
Error forking process
In parent process
Error forking process
In parent process

Similar Posts