Python 子进程模块在段错误时不返回标准输出

2022-01-12 00:00:00 python subprocess segmentation-fault

问题描述

我正在从 Python 运行一个 C 可执行文件,这个可执行文件有时会出现段错误.当它发生段错误时,子进程模块不会在 stdout 或 stderr 中返回任何内容.

I'm running a C executable from Python and this executable sometimes segfaults. When it segfaults the subprocess module does not return anything in stdout or stderr.

示例代码:

import subprocess

proc = subprocess.Popen(['./a.out'], stdin=subprocess.PIPE,
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate()
print 'out: "%s"' % out
print 'err: "%s"' % err
print proc.returncode

a.out的来源是:

int main() {
    printf("hello world
");
    int x = 1 / 0;
}

./a.out的输出是:

hello world
Floating point exception

Python 代码的输出是(在 Linux 中,python 2.7):

The output of the Python code is (in Linux, python 2.7):

out: ""
err: ""
-8

有没有办法在可执行文件崩溃的情况下获取它的输出?

Is there a way to get the output of the executable even if it crashes?

将返回码转换为字符串消息的通用方法也不错.

A generic method to translate returncode to a string message, would also be nice.


解决方案

你的 C 程序没有刷新它的输出缓冲区.解决此问题的最简单方法是将 STDOUT 的输出模式更改为无缓冲:

Your C program is not flushing its output buffer. The easiest way around this problem is to change the output mode of STDOUT to unbuffered:

#include <stdio.h>
int main(int argc,char **argv) {
    setvbuf(stdout,_IONBF,0,0);
    printf("hello world
");
    int x = 1 / 0;
}

现在您的程序(我对其进行了编辑以修复错字)产生了正确的输出:

Now your program (which I edited to fix a typo) produces the correct output:

$ python2.7 x.py
out: "hello world
"
err: ""
0
$

在我的 Mac 上返回码是 0,令人困惑,因为因信号而终止的程序没有返回码.

The return code is 0 on my Mac, confusingly, because programs that are terminated for a signal don't have a return code.

相关文章