In python, the fork () function is used to generate sub-processes. in the OS module of python, the fork () function is used to generate sub-processes. the generated sub-process is the image of the parent process, however, they have their own address space. The child process replicates a parent process memory to itself, and the execution between the two processes is independent of each other, the execution sequence can be uncertain, random, and unpredictable, which is similar to the execution sequence of multiple threads.
import osdef child(): print 'A new child:', os.getpid() print 'Parent id is:', os.getppid() os._exit(0)def parent(): 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 load the OS module, the fork () function in our parent function generates a sub-process. The return value of newpid has two, and one is 0, which indicates the sub-process, an integer greater than 0 is used to represent the parent process. This constant is the pid of the child process. the print statement clearly shows two return values. If fork () returns a negative value, it indicates that the sub-process is not successfully generated (this is not considered in this simple program ). If newpid = 0, it indicates that we enter the child process, that is, the child () function. in the child process, we output our own id and the parent process id. If the else statement is entered, it indicates that newpid> 0, we enter the parent process, in the parent process OS. getpid () gets its own id. fork () returns newpid, which indicates the id of the child process. at the same time, we output the id of the parent process. through the experiment, we can see that the execution sequence of if and else statements is uncertain. the execution sequence of sub-and parent processes is determined by the scheduling algorithm of the operating system.