This article mainly introduces the fork () function generated in Python, analyze the order of execution of the subprocess and the parent process, and the friends who need it can refer to the following
Python's OS module has the fork () function for generating child processes, the generated subprocess is a mirror image of the parent process, but they have their own address space, and the child processes the memory of the parent process to itself, and the execution of the two processes is independent of each other, and the order of execution can be indeterminate, random, Unpredictable, this is similar to the order in which multithreading is executed.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17-18 |
Import OS def child (): print ' A new child: ', Os.getpid () print ' Parent ID is: ', Os.getppid () os._exit (0) def Parent (): WHI Le true:newpid=os.fork () print newpid if Newpid==0:child () else:pids= (Os.getpid (), newpid) print "parent:%d,child:%d"%p IDS print "Parent parent:", Os.getppid () if raw_input () = = ' Q ': Break parent () |
After we load the OS module, the fork () function in our parent function generates a subprocess, the return value Newpid two, one is 0, to represent the subprocess, and the integer greater than 0 to represent the parent process, which is the PID of the child process. With the print statement we can see clearly two return values. If the fork () return value is negative, the child process generation is unsuccessful (this is not considered in this simple program). If newpid==0, it means that we are in the subprocess, the child () function, in which we output our ID and the ID of the parent process. If the Else statement is entered, it indicates that newpid>0, we go into the parent process, os.getpid () in the parent process () gets its own id,fork () return value NEWPID represents the ID of the child process, and we output the ID of the parent process. Through experiments we can see that if and ELSE statements are executed in an indeterminate order, the execution order of the child and the parent process is determined by the operating system's scheduling algorithm.