Summary Python use fork to create child process considerations _python

Source: Internet
Author: User

I have written the test code for the fork process under Python (to show that the problem is not necessarily 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 ' sub-process [%s]:%s '% (now (), Os.getpid ()) while
  1:
   a-=10
   print ' child process's a value [%s]:%s '% (now (), a)
   if a < 1: the break
  print ' prepares to exit the subprocess '
  #os. _exit (0) # # You can exit the subprocess here
 else:
  print ' parent process [%s]:%s '% (now (), Os.getpid ()) while
  1:
   a-=1
   print ' parent process ' a value [%s] :%s '% (now (), a)
   if a < 0:
    break
  time.sleep (1)
  print ' Waits for child process to end ... '
  try: result
   = Os.wait ()
   if result:
    print ' child process: ', result[0], result[1]
   else:
    print ' no data! '
  Except:
   print ' abnormal oh ... ' print '
  parent process ... '
 print ' last value: ', a
 #exit (0) # # You can also exit here, note that this is where both the parent and child processes share , exiting here will cause the parent process to also exit

TIPS:

Os.fork () will have two return values, respectively, for the parent process and the child process
In the parent process, the value returned by the fork is the PID of the child process;
Child process, this return value is 0
The child process copies the context of the parent process
The parent-child process does not determine the order of execution
After Os.fork (), the child process must use Exit () or Os._exit () to exit the subprocess environment and recommend the use of Os._exit ()
The code that os.fork () to create the subprocess is not very adaptable, Linux is OK, it is not available under Windows, and official documents have similar statements:

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.