Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
关于Python中的os.fork()函数_Python_Fork - Fatal编程技术网

关于Python中的os.fork()函数

关于Python中的os.fork()函数,python,fork,Python,Fork,我刚开始学习python,我开发了一个简单的程序来派生父进程。这是我到目前为止写的代码 #!/usr/bin/env python import os def child(): print "We are in the child process with PID= %d"%os.getpid() def parent(): print "We are in the parent process with PID= %d"%os.getpid() newRef=os.

我刚开始学习python,我开发了一个简单的程序来派生父进程。这是我到目前为止写的代码

#!/usr/bin/env python
import os

def child():
    print "We are in the child process with PID= %d"%os.getpid()

def parent():
    print "We are in the parent process with PID= %d"%os.getpid()
    newRef=os.fork()
    if newRef==0:
        child()
    else:
        print "We are in the parent process and our child process has PID= %d"%newRef

parent()
据我所知,代码应该从调用父进程开始,并显示其PID。之后,调用
os.fork()
并创建父进程的副本,由于我们已经在父进程中,
newRef
变量应该包含一个正值,而我的代码的
else
部分应该被执行。我的问题是:尽管我的代码中的
if
部分不应该执行,但为什么代码随后启动调用
child()
函数呢


提前感谢:)

当您调用
os.fork
时,您创建了一个与现有进程完全相同的新进程,但在原始进程中,
fork
返回新(子)进程的进程ID,在新进程中,
fork
返回
0
。这种差异就是你如何在父母和孩子身上做一些不同的事情


在特定代码中,子进程中的
fork
的返回值为
0
,因此子进程调用
child
函数。在父级中,返回值不是
0
,因此执行else子句。

fork
返回后,现在有两个进程在
fork
之后立即执行代码

因此,你的声明:

因为我们已经在父进程中


这只是事实的一半。在
os.fork
返回后,父进程继续执行与父进程相同的代码,但子进程继续使用相同的局部和全局变量执行完全相同的代码,返回值
fork
除外。因此,从子进程的角度来看,
newRef
的值为
0
,而从父进程的角度来看,
newRef
的值为正值。这两个进程都将相应地执行代码。

当它们变得更复杂时,绝对需要跟踪它们。需要记住的一点是,当您调用fork()函数时,它会在该点创建当前进程的精确内存副本。尝试运行
if fork()!=fork():fork()