gpt4 book ai didi

python - 有人可以向我解释以下 os.fork() 示例吗?

转载 作者:太空狗 更新时间:2023-10-29 20:21:32 26 4
gpt4 key购买 nike

[代码取自 Mark Lutz 编写的 Programming Python 4th Edition]

"forks child processes until you type 'q'"
import os
def child():
print('Hello from child', os.getpid())
os._exit(0) # else goes back to parent loop

def parent():
while True:
newpid = os.fork()
if newpid == 0:
child()
else:
print('Hello from parent', os.getpid(), newpid)
if input() == 'q': break

parent()

运行时代码输出的内容:

Hello from parent 2057 2062 
Hello from child 2062

Hello from parent 2057 2068
Hello from child 2068

Hello from parent 2057 2069
Hello from child 2069

Hello from parent 2057 2070
Hello from child 2070
q

我的理解:

  1. os.fork() 用于启动与当前进程并行的另一个进程。
  2. os.fork() 创建先前 Python session 的副本并并行打开它。
  3. os.fork() 返回新进程的 ID。

我不明白的地方:

  1. 为什么 os.getpid() 的值在代码运行时从未改变?
  2. 为什么要调用 child() 函数?假设 newpid 的值 != 0,那么程序将打印出 print('Hello from parent', os.getpid(), newpid)。但是,在那之后,它会打印来自 child 的行,而不是要求输入,因为这种情况是在 if 语句之后。
  3. os._exit(0) 在做什么?

非常感谢您的宝贵时间。 :)

最佳答案

1: How come the value of os.getpid() is never changed when the code runs?

os.getpid() 的值对于父进程永远不会改变,因为这始终是相同的进程。由于 fork() 总是使用自己的 PID 创建全新的子进程克隆,因此每次子进程的 pid 都会更改。

2: Why is the child() function ever called? Let's say that the value of newpid != 0, then the program will print out print('Hello from parent', os.getpid(), newpid). However, after that, it prints the line from child rather than asking for an input as the case is after the if statement.

调用子进程是因为现在有两个进程在运行。一个调用 child() 函数,另一个调用 print 函数。他们只是在为打印到屏幕而战,在这种情况下,您看到父级首先打印“win”。

3: What is os._exit(0) doing?

参见此处:https://docs.python.org/2/library/os.html#os._exit

Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc.

关于python - 有人可以向我解释以下 os.fork() 示例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24052217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com