Summary Python USES fork to create child process considerations

  • 2020-04-02 13:48:59
  • OfStack

I wrote the test code for the fork process in Python (to illustrate that this problem is not entirely appropriate) :


def fork(a):
 def now():
  import datetime
  return datetime.datetime.now().strftime("%S.%f")
 import os
 import time
 print now(), a
 if os.fork() == 0:
  print ' The child process [%s]:%s' % (now(), os.getpid())
  while 1:
   a-=10
   print ' The child's a value [%s] : %s' % (now(), a)
   if a < 1:
    break
  print ' Ready to exit the child process '
  #os._exit(0) ##  You can exit the child process here 
 else:
  print ' The parent process [%s]:%s' % (now(), os.getpid())
  while 1:
   a-=1
   print ' The parent of a value [%s] : %s' % (now(), a)
   if a < 0:
    break
  time.sleep(1)
  print ' Wait for the child process to finish ...'
  try:
   result = os.wait()
   if result:
    print ' The child process :', result[0], result[1]
   else:
    print ' There is no data !'
  except:
   print ' Abnormal oh ...'
  print ' The parent process ...'
 print ' Final value: ',a
 #exit(0) ##  You can also exit here. Note that this is where both the parent and child processes are Shared 

TIPS:

Os.fork () returns the value of the parent and child process twice
In the parent process, the value returned by fork is the PID of the child process.
In the child process, the return value is 0
The child process copies the context of the parent process
The parent and child processes do not determine the order of execution
After os.fork(), the child process must exit() or os._exit() to exit the child process environment. Os._exit () is recommended.
Os. fork() is not a very good code to create a child process, Linux is fine, but it does not work under Windows, and the official documentation says something like this:


Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have known issues when using fork() from a thread
Availability: Unix.


Related articles: