Python:os.fork()如何工作? [英] Python:How os.fork() works?

查看:64
本文介绍了Python:os.fork()如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习python中的多处理.我尝试了多处理,在阅读了多处理模块的源代码之后,我发现它使用了os.fork(),因此我编写了一些代码来测试os.fork(),但是我被卡住了.我的代码如下:

I am learning multiprocessing in python. I tried multiprocessing and after I read the source code of multiprocessing module, I found it use os.fork(), so I wrote some code to test os.fork(), but I am stuck. My code is as following:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import time

for i in range(2):
    print '**********%d***********' % i
    pid = os.fork()
    print "Pid %d" % pid

我认为每次打印将执行两次,但它们将执行三次.我不明白这是怎么回事? 我阅读了需要了解fork的工作原理?
根据本文的说法,它也会被执行两次,所以我很困惑……

I think that each print will be executed two times but they execute three times. I can't understand how this works? I read this Need to know how fork works?
From what this article says it also will be executed twice, so I am so stuck...

推荐答案

要直接回答该问题,os.fork()通过调用底层OS函数fork()起作用.

To answer the question directly, os.fork() works by calling the underlying OS function fork().

但是您肯定对它的作用感兴趣.好吧,这创建了另一个过程,该过程将在与此完全相同的地方恢复.因此,在第一个循环运行中,您将获得一个派生,其后有两个进程,原始进程"(获得子进程的PID的pid值)和分叉的进程(获得pid0).

But you are surely interested in what this does. Well this creates another process which will resume at exactly the same place as this one. So within the first loop run, you get a fork after which you have two processes, the "original one" (which gets a pid value of the PID of the child process) and the forked one (which gets a pid value of 0).

它们都打印其pid值,并继续进行第二个循环运行,并同时打印它们.然后它们都分叉,给您留下4个进程,它们全部打印各自的pid值.其中两个应该是0,另外两个应该是它们刚创建的子代的PID.

They both print their pid value and go on with the 2nd loop run, which they both print. Then they both fork, leaving you with 4 processes which all print their respective pid values. Two of them should be 0, the other two should be the PIDs of the child they just created.

将代码更改为

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import time

for i in range(2):
    print '**********%d***********' % i
    pid = os.fork()
    if pid == 0:
        # We are in the child process.
        print "%d (child) just was created by %d." % (os.getpid(), os.getppid())
    else:
        # We are in the parent process.
        print "%d (parent) just created %d." % (os.getpid(), pid)

您会更好地看到会发生什么:每个进程都会告诉您自己的PID以及分叉发生了什么.

you will see better what happens: each process will tell you its own PID and what happened on the fork.

这篇关于Python:os.fork()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆