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.