简体   繁体   English

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

[英]Regarding The os.fork() Function In Python

I'm just beginning with python and I developed a simple program to fork a parent process. 我刚刚开始使用python,我开发了一个简单的程序来分叉父进程。 Here's the code I've written so far... 这是我到目前为止编写的代码......

#!/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()

From what I understand, the code should begin by calling the parent process and display its PID. 根据我的理解,代码应该从调用父进程开始并显示其PID。 Afterwards, the os.fork() is called and it creates a copy of the parent process, and since we are already in the parent process, the newRef variable should contain a value that is positive and the else part of my code is the one that should be executed. 之后,调用os.fork()并创建父进程的副本,因为我们已经在父进程中,所以newRef变量应该包含一个肯定的值,而我的代码的else部分是一个应该执行。 My question is that: why did the code initiate to call the child() function afterwards although the if part of my code should not execute. 我的问题是:为什么代码会在之后启动调用child()函数,尽管我的代码的if部分不应该执行。

Thanks in advance :) 提前致谢 :)

After you return from fork , you now have two processes executing the code immediately following fork . fork返回后,您现在有两个进程fork立即执行代码。

So your statement: 所以你的声明:

since we are already in the parent process 因为我们已经在父进程中了

is only half-true. 只是半真的。 After os.fork returns, the parent process continues executing the code as the parent process, but the child process continues executing the exact same code with the same local and global variables, with the exception of the return value of fork . os.fork返回之后,父进程继续执行代码作为父进程,但子进程继续执行具有相同本地和全局变量的完全相同的代码 ,但fork的返回值除外。 So, from the child process's perspective, newRef has the value of 0 , and from the parent's perspective, newRef has a positive value. 因此,从子进程的角度来看, newRef的值为0 ,从父级的角度来看, newRef的值为正值。 Both processes will execute the code accordingly. 两个进程都将相应地执行代码。

When you call os.fork , you create a new process that is an exact copy of the existing process except that in the original process, fork returns the process ID of the new (child) process, and in the new process, fork returns 0 . 当你调用os.fork ,你创建一个新进程,它是现有进程的精确副本, 除了在原始进程中, fork返回新(子)进程的进程ID,并且在新进程中, fork返回0 This difference is how you can do something different in the parent and in the child. 这种差异就是你如何在父母和孩子身上做出不同的事情。

In your specific code, the return value of fork in the child is 0 , so the child process calls the child function. 在您的特定代码中,子项中fork的返回值为0 ,因此子进程调用child In the parent, the return value is not 0 , so the else clause is executed. 在父级中,返回值不为0 ,因此执行else子句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM