Subprocesses generated using the fork () function in Python
This article mainly introduces the subprocesses generated using the fork () function in Python, and analyzes the execution sequence of The subprocesses and parent processes. For more information, see
In the python OS module, the fork () function is used to generate sub-processes. The generated sub-processes are the mirror of the parent process, but they have their own address space, the sub-process replicates the parent process memory to itself. The execution between the two processes is independent of each other, and the execution sequence can be uncertain, random, and unpredictable, this is similar to the execution sequence of multiple threads.
?
|
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 ():
While True:
Newpid = OS. fork ()
Print newpid
If newpid = 0:
Child ()
Else:
Pids = (OS. getpid (), newpid)
Print "parent: % d, child: % d" % pids
Print "parent:", OS. getppid ()
If raw_input () = 'q ':
Break
Parent ()
|
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.