python fork_python多进程——fork()

简介

程序每次执行时,操作系统都会创建一个新进程来运行程序指令。进程中可调用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 =&

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值