Linux系统提供了一个fork()函数创建子进程。当调用这个函数时,操作系统将当前的进程(父进程)复制一份(子进程),然后分别在父进程和子进程内返回,子进程永远返回0,父进程返回子进程的PID
python中os模块提供了fork()函数
import os
import time
print("Before fork process pid=%s, ppid=%s" % (os.getpid(), os.getppid()))
pid = os.fork()
if pid == 0:
print("I am child process pid=%s, ppid=%s" % (os.getpid(), os.getppid()))
time.sleep(5)
else:
print("I am parent process pid=%s, ppid=%s" % (os.getpid(), os.getppid()))
time.sleep(5)
print( "After fork process pid=%s, ppid=%s" % (os.getpid(), os.getppid()))
运行结果:
Before fork process pid=8161, ppid=6182
I am parent process pid=8161, ppid=6182
I am child process pid=8162, ppid=8161
After fork process pid=8162, ppid=8161
After fork process pid=8161, ppid=6182