python - 如果我在子进程中输入一些内容,fork 和 exec 组合将不起作用

标签 python io terminal fork

我写了一个 python 代码,其中一个进程使用 fork() 创建另一个进程。在子进程中,我想使用 execlp() 打开另一个进程。

我在子进程中打开的程序显示EOF 错误。我不明白为什么,因为当我尝试单独运行该子程序时,它没有显示任何错误。

对于主要过程,Python 代码是

import os  
def main():  
        pid=os.fork()  
        if pid==0:  
                os.execlp("python3", "python3", "child1.py")  
        else:  
                print("I am parent")  
main() 

对于子进程的代码是

def main():  
  a=input("enter a no : ")  
  print("I am child "+str(a))  
main() 

我打开主程序或者父进程得到的输出是

I am parent
debesh@laptop:~/Documents/programs/python/parallel_processes$ enter a no : Traceback (most recent call last):
  File "child1.py", line 5, in <module>
    main()
  File "child1.py", line 2, in main
    a=input("enter a no : ")
EOFError

最佳答案

child 试图在其 parent 去世后从终端读取。这不起作用,因为子进程不再位于前台进程组中。

好的,什么是前台进程组?基本思想是 process group同一 shell 作业中的一组进程。当您从终端中的 shell 运行程序时,shell 会为该程序创建一个进程组。如果程序 fork ,则子进程属于同一个进程组。如果您在后台运行该程序 (myprogram &),进程组是一个 background process group ;如果你在前台运行程序(没有&)那么进程组是foreground process group (只能有一个前台进程组)。 shell 命令fgbg 可以将进程组带入前台或后台。进程组用于两件事:您可以将它们一起发信号,它们决定允许谁访问终端。

只允许前台进程组从终端读取。如果后台进程试图从终端读取,read系统调用返回 EIO。这是一个用户界面设计决策:当用户在前台与程序交互时,后台进程不会中断它。

让我们让子进程打印有关其进程组的信息:

#!/usr/bin/python3
import os
def main():  
  print("Child: pid={pid:d} ppid={ppid:d} pgid={pgid:d}".format(pid=os.getpid(), ppid=os.getppid(), pgid=os.getpgrp()))
  a=input("enter a no : ")  
  print("I am child "+str(a))  
main() 

示例输出:

$ ./parent.py 
I am parent
$ Child: pid=15593 ppid=1 pgid=15592
enter a no : Traceback (most recent call last):
  File "child1.py", line 7, in <module>
    main() 
  File "child1.py", line 5, in main
    a=input("enter a no : ")  
EOFError

子进程组还是父进程ID,但是父进程已经死了(所以现在子进程的父进程ID为1)。因此, child 现在处于自己的进程组中。由于它不在前台(shell现在回到前台), child 在后台,所以它无法访问终端。

对比如果在 print("I am parent") 之前添加对 os.wait() 的调用会发生什么:

$ ./parent.py 
Child: pid=15619 ppid=15618 pgid=15618
enter a no : hello
I am child hello
I am parent

这次子进程还在前台进程组中,所以它可以正常访问终端。

我不知道为什么 Python 将错误报告为 EOFError 而不是 IOError

关于python - 如果我在子进程中输入一些内容,fork 和 exec 组合将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28645598/

相关文章:

python - 替代 u'string'

python - 我可以在Python中同时进行变量赋值和列表插入吗?

java - java中逐列求和

mysql - 寻找 MySQL 默认昨天日期

python 子进程不能很好地使用 gsutil 复制/移动命令

Python 加载 windows 库 C# 转换

python - Gunicorn 多处理中的原子代码/仅在工作程序 1 中运行代码?

c# - Process.Start 找不到现有文件

java - 在可序列化对象上获取 NotSerializableException

regex - grep XML 值,如果包含数字则将其导出