Python's OS module has a fork () function for generating child processes, the resulting child processes are mirrors of the parent process, but they have their own address space, and the child process copies a copy of the parent process memory to itself, and the execution of the two processes is independent of each other, and the order of execution can be indeterminate, random, Unpredictable, and this is similar to the order in which multithreading is executed.
Import Osdef Child (): print ' A new child: ', Os.getpid () print ' Parent ID is: ', Os.getppid () os._exit (0) def PA Rent (): While True: newpid=os.fork () print newpid if newpid==0: Child () Else: pids= ( Os.getpid (), newpid) print "parent:%d,child:%d"%pids print "Parent parent:", Os.getppid () if raw_ Input () = = ' Q ': breakparent ()
After we loaded the OS module, our parent function in the fork () function generated a child process, the return value Newpid has two, one is 0, to represent the child process, one is greater than 0 integer, to represent the parent process, this constant is the PID of the child process. With the print statement we can see two of the return values clearly. If the fork () return value is a negative number, the child process generation is unsuccessful (this is not considered in this simple program). If newpid==0, it indicates that we entered the subprocess, the child () function, in which we output our own ID and the ID of the parent process. If the Else statement is entered, it indicates that newpid>0, we enter into the parent process, os.getpid () The parent process to get its own id,fork () return value Newpid represents the child process ID, and we output the parent process's parent process ID. Through experiments we can see that the order of execution of the IF and else statements is indeterminate, and the order of execution of the child and the parent process is determined by the operating system's scheduling algorithm.