简体   繁体   English

python os.fork() 的返回值是多少?

[英]What are the returned values of python os.fork()?

Python os.pipe() and os.fork() are new to me and I have a few basic questions about them. Python os.pipe()os.fork()对我来说是新的,我有一些关于它们的基本问题。 There is a code taken from here as follows:这里获取的代码如下:

# Python program to explain os.fork() method

# importing os module
import os


# Create a child process
# using os.fork() method
pid = os.fork()

# pid greater than 0 represents
# the parent process
if pid > 0 :
    print("I am parent process:")
    print("Process ID:", os.getpid())
    print("Child's process ID:", pid)

# pid equal to 0 represents
# the created child process
else :
    print("\nI am child process:")
    print("Process ID:", os.getpid())
    print("Parent's process ID:", os.getppid())


# If any error occurred while
# using os.fork() method
# OSError will be raised

and the output is: output 是:

I am Parent process
Process ID: 10793
Child's process ID: 10794

I am child process
Process ID: 10794
Parent's process ID: 10793

When I print out pid , two integers are displayed, one of which is always 0. According to the code comments, pid greater than 0 represents the parent process , if this is the case then why inside if pid > 0 block, which means pid value corresponds to the parent, there is print("Child's process ID:", pid) where the value of pid is associated with the child's process ID?当我打印出pid时,显示了两个整数,其中一个始终为 0。根据代码注释, pid 大于 0 表示父进程,如果是这样那么为什么里面if pid > 0块,这意味着 pid value对应parent,有print("Child's process ID:", pid)其中pid的值与child的进程ID相关联? Also, as pid returns two values how are they handled in both if and else statements as according to the output both if and else are executed?此外,由于pid返回两个值,如何在ifelse语句中处理它们,如 output ifelse都被执行?

According to the documentation: os.fork() return 0 in the child and the child's process id in the parent.根据文档:os.fork() 在子进程中返回 0,在父进程中返回子进程 ID。 If an error occurs OSError is raised.如果发生错误,则会引发 OSError。

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

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