Python中,通过os.fork()会做下面的事情
(1)创建子进程,子进程会复制父进程的数据信息,然后程序就分两个进程继续运行后面的程序,这也是fork(分叉)名字的含义了。
(2)在父进程内,这个方法会返回子进程的编号PID。
(3)在子进程内,这个方法会返回0。
所以可以使用PID来区分两个进程:
import os
def doing():
print '{} : before fork'.format(os.getpid())
pid = os.fork()
#复制出来的子进程会在这里继续执行,同时pid=0
print '{} : after fork'.format(os.getpid())
if pid == 0:
# We are in the child process.
print "{} (child) was created by {}.".format(os.getpid(), os.getppid())
else:
# We are in the parent process.
print "{} (parent) created {}.".format(os.getpid(), pid)
print '{} : end'.format(os.getpid())
print '************************'
if __name__ == '__main__':
doing()
85925 : before fork
85925 : after fork
85925 (parent) created 85926.
85925 : end
************************
85926 : after fork
85926 (child) was created by 85925.
85926 : end
************************
Process finished with exit code 0