进程管理 [一]




os.fork函数


[root@lvdbing python]# cat os_fork.py
#!/usr/bin/env python
# Using fork to create child processes
# Author: lvDbing
# Date : 2008-09-23
import os
import sys
import time
processName = "parent"
print "Program executing \n\tpid: %d, processName: %s" % (os.getpid(), processName)
# attempt to fork child process
try:
        forkPID = os.fork()
except OSError:
        sys.exit("Unable to create new process.")
# Am I parent process?
if forkPID != 0:
        print "Parent executing\n" + "\tpid: %d, forkPID: %d, processName: %s" % (os.getpid(), forkPID, processName)
# Am I child process?
elif forkPID == 0:
        processName = "child"
        print "Child executing\n" + "\tpid: %d, forkPID: %d, processName: %s" % (os.getpid(), forkPID, processName)
print "Process finishing\n\tpid: %d, processName: %s" % (os.getpid(), processName)
程序每次执行时,操作系统就会创建一个新的进程来运行程序指令。进程还可以调用os.fork,要求操作系统新建一个进程。“父进程”是调用os.fork的进程。父进程所创建的任何进程都是子进程。每个进程都有一个不重复的“进程ID号”,或称“pid”,它对进程进程进行标识。
进程调用fork函数时,操作系统会新建一个子进程,它本质上与父进程完全相同。子进程从父进程继承了多个值的拷贝,比如全局变量和环境变量。两个进程唯一的区别就是fork的返回值。
child(子)进程接收返回值为0,而父进程接收子进程的pid作为返回值。调用fork函数后,两个进程并发执行同一个程序,首先执行的是调用了fork之后的下一行代码。父进程和子进程既并发执行,又相互独立;也就是说,它们是“异步执行”的。
[root@lvdbing python]# ./os_fork.py
Program executing
        pid: 4404, processName: parent
Parent executing
        pid: 4404, forkPID: 4405, processName: parent
Child executing
        pid: 4405, forkPID: 0, processName: child
Process finishing
        pid: 4405, processName: child
Process finishing
        pid: 4404, processName: parent