Home  >  Article  >  Backend Development  >  Analysis of subprocess generated by fork() function in python

Analysis of subprocess generated by fork() function in python

高洛峰
高洛峰Original
2016-10-18 10:02:311081browse

Python's os module has the fork() function for generating child processes. The generated child processes are mirror images of the parent process, but they have their own address spaces. The child process copies a copy of the parent process memory to itself. Between the two processes The executions are independent of each other, and their execution order can be uncertain, random, and unpredictable, which is similar to the execution order of multi-threads.

import os
def 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':
            break
parent()

After we load the os module, the fork() function in our parent function generates a child process. There are two return values ​​​​newpid, one is 0, used to represent the child process, and the other is an integer greater than 0, used To represent the parent process, this constant is the pid of the child process. We can clearly see the two return values ​​through the print statement. If the return value of fork() is a negative value, it indicates that the child process was not successfully generated (this situation is not considered in this simple program). If newpid==0, it means that we have entered the child process, that is, the child() function. In the child process, we output our own id and the id of the parent process. If the else statement is entered, it means newpid>0, and we enter the parent process. In the parent process, os.getpid() gets its own id. The return value of fork(), newpid, represents the id of the child process. At the same time, we output The ID of the parent process of the parent process. Through experiments, we can see that the execution order of if and else statements is uncertain. The execution order of child and parent processes is determined by the scheduling algorithm of the operating system.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn