简介
程序每次执行时,操作系统都会创建一个新进程来运行程序指令。进程中可调用os.fork,要求操作系统新建一个子进程.[Windowsc系统中,os模块没有os.fork函数]。
每个进程都有一个不重复的进程ID号。或称pid,它对进程进行标识。子进程与父进程完全相同,子进程从父进程继承了多个值的拷贝。如全局变量和环境变量。fork后,子进程接收返回值0,而父进程接收子进程的pid作为返回值
os.fork()
Fork a child process.Return 0 in the child and the child’s process id in the parent.If an error occurs OSError is raised.
Note that some platforms including FreeBSD <= 6.3 and Cygwin have known issues when using fork() from a thread.
Availability: Unix> 仅支持基于Unix核心的系统
(一)fork函数在子进程中返回0,在父进程中返回子进程的id:
os.getpid() 返回进程pid
os.getppid() 返回父进程pid
#-*-coding:utf-8-*-
importosimporttimeprint('before calling')
p= os.fork() #主进程,子进程同时向下执行
print('after calling')if p ==0:print('执行子进程, pid={} ppid={} p={}'.format(os.getpid(), os.getppid(), p))else:print('执行主进程, pid={} ppid={} p={}'.format(os.getpid(), os.getppid(), p))
[root@192 ~]# python fork.py
before calling
after calling
执行主进程, pid=1629 ppid=1572 p=1630
after calling
执行子进程, pid=1630 ppid=1629 p=0
结论:调用os.fork()之后,主进程和子进程同时执行该行以下的代码,子进程中fork函数返回0,父进程中返回1630,即子进程的pid.
再看下面的代码结果:
#-*-coding:utf-8-*-
importosimporttimeprint('before calling')
p= os.fork() #主进程,子进程同时向下执行
print('after calling')if p =&