使用 Python 实现多进程
2010-09-22 11:23:22 来源:WEB开发网现在来看一下以上代码的输出:
mac% python fork.py
Parent Process: PID# 5285
Child Process: PID# 5286
在下一个示例中,增强初始 fork 的代码,并设置一个环境变量。该环境变量随后将被复制到子进程中。下面给出了相应的代码:
示例 1. Python 中的 fork 操作
#!/usr/bin/env python
"""A fork that demonstrates a copied environment"""
import os
from os import environ
def my_fork():
environ['FOO']="baz"
print "FOO environmental variable set to: %s" % environ['FOO']
environ['FOO']="bar"
print "FOO environmental variable changed to: %s" % environ['FOO']
child_pid = os.fork()
if child_pid == 0:
print "Child Process: PID# %s" % os.getpid()
print "Child FOO environmental variable == %s" % environ['FOO']
else:
print "Parent Process: PID# %s" % os.getpid()
print "Parent FOO environmental variable == %s" % environ['FOO']
if __name__ == "__main__":
my_fork()
下面给出了 fork 的输出: mac% python env_fork.py
FOO environmental variable set to: baz
FOO environmental variable changed to: bar
Parent Process: PID# 5333
Parent FOO environmental variable == bar
Child Process: PID# 5334
Child FOO environmental variable == bar
更多精彩
赞助商链接