以python代码解释fork系统调用

import os

print('Process (%s) start...' % os.getpid())
# Only works on Unix/Linux/Mac:
pid = os.fork()
print ("haha")
if pid == 0:
print('I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid()))
else:
print('I (%s) just created a child process (%s).' % (os.getpid(), pid)) """
haha
haha
Process (876) start...
I (876) just created a child process (877).
I am child process (877) and my parent is 876.
"""

执行到os.fork()时,发起fork系统调用,操作系统复制父进程得到子进程。fork系统调用完毕,返回给父进程子进程的id号,返回给子进程0,然后父子进城开始执行。我们可以看到haha被打印了两次,更加说明了子进程是复制父进程得来的

再举个例子,说明子金成是复制父进程:

print("This is console module")

from multiprocessing import Process
import os
import time
ppp=3
def run_proc(name):
print('Run child process %s (%s)...' % (name, os.getpid()),ppp) #观察这句的执行结果
if __name__=='__main__':
print('Parent process %s.' % os.getpid())
p = Process(target=run_proc, args=('test',))
print('Child process will start.')
p.start()
#p.join()
print('Child process end.') """
Parent process 928.
Process will start.
Run child process test (929)...,3
Process end.
"""

子进程正常打印了ppp的变量,说明子金城不仅仅是复制了实际的执行函数run_proc,而是复制了父进程全部的代码,所以才能正常打印ppp变量

上一篇:即时通信WebSocket 和Socket.IO


下一篇:Python 创建简单的本地HTTP服务器