Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.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/5/bash/15.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 获取子流程中分叉流程的标准输出/标准输出_Python_Fork_Subprocess_Stdout_Stderr - Fatal编程技术网

Python 获取子流程中分叉流程的标准输出/标准输出

Python 获取子流程中分叉流程的标准输出/标准输出,python,fork,subprocess,stdout,stderr,Python,Fork,Subprocess,Stdout,Stderr,我有一个C程序,它调用fork() 我有一个python脚本,它用 child = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE,stdout=subprocess.PIPE, bufsize=0) 现在,我可以使用child.stderr.read(1)或child.communicate()。。。但我现在的问题是,如何只从分叉过程中获得输出。这可能吗?我可以从原始的C程序和fork中得到pid吗 亲切问候,, 非常

我有一个C程序,它调用
fork()

我有一个python脚本,它用

child = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE,stdout=subprocess.PIPE, bufsize=0)
现在,我可以使用
child.stderr.read(1)
child.communicate()
。。。但我现在的问题是,如何只从分叉过程中获得输出。这可能吗?我可以从原始的C程序和fork中得到pid吗

亲切问候,, 非常感谢:)


Fabian

您所要求的将是复杂的,在纯python中是不可能实现的——您将需要一些特定于操作系统的机制

你真的在要求两件事:

  • 从父进程的PID中标识分叉进程
  • 截取任意进程中的标准输入/输出
如果您在Linux上,您可能可以通过解析/proc来实现前者,后者实际上是一个类似于调试器的功能(例如)

更可能的情况是,您希望更改C程序的工作方式——例如,从python脚本而不是中间C代码执行fork()/daemonization可以让您直接获得子进程。

我认为,当您在C中执行fork()进程时,您不能将任何描述符从子进程传递回父进程,但可能是我错了。唯一得到的是新子进程的PID。最好的方法应该是打开一个管道(使用常规名称,例如管道名称包含进程的PID),然后可以从任何位置打开该管道

最后,当您执行fork()过程时,它会给您PID,您可以将PID(C二进制和forked)写入C程序的标准输出,例如,使用分隔符:

cpid = fork();
printf("%d|%d", (int)get_pid(), cpid);

祝你好运:)

“这可能吗?”否。“我可以从原始C程序和fork中同时获得pid吗?”否。C程序拥有该子程序。您的进程拥有C程序。现在。不要再担心Linux的细节,描述一下你真正的问题。为什么Python程序不能运行与C程序相同的子进程?更简单的方法可能是使用不同的输出格式,主进程可以从“ParentOutput:”开始,而子进程的输出是:“ChildOutput:”。然后您可以忽略python程序中的“ParentOutput”。