2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > python子进程关闭fd_python – 捕获崩溃的子进程的“分段错误”...

python子进程关闭fd_python – 捕获崩溃的子进程的“分段错误”...

时间:2022-04-04 20:47:05

相关推荐

python子进程关闭fd_python  – 捕获崩溃的子进程的“分段错误”...

shell可能会生成“Segmentation fault”消息.要找出该过程是否被SIGSEGV杀死,请检查proc.returncode == -signal.SIGSEGV.

如果要查看消息,可以在shell中运行该命令:

#!/usr/bin/env python

from subprocess import Popen, PIPE

proc = Popen(shell_command, shell=True, stdout=PIPE, stderr=PIPE)

out, err = municate()

print out, err, proc.returncode

我已经用ctypes import *; memset(0,1,1)’中的shell_command =“python -c”测试了它,导致了段错误并且错误捕获了消息.

如果消息直接打印到终端,那么您可以使用pexpect模块捕获它:

#!/usr/bin/env python

from pipes import quote

from pexpect import run # $pip install pexpect

out, returncode = run("sh -c " + quote(shell_command), withexitstatus=1)

signal = returncode - 128 # 128+n

print out, signal

或直接使用pty stdlib模块:

#!/usr/bin/env python

import os

import pty

from select import select

from subprocess import Popen, STDOUT

# use pseudo-tty to capture output printed directly to the terminal

master_fd, slave_fd = pty.openpty()

p = Popen(shell_command, shell=True, stdin=slave_fd, stdout=slave_fd,

stderr=STDOUT, close_fds=True)

buf = []

while True:

if select([master_fd], [], [], 0.04)[0]: # has something to read

data = os.read(master_fd, 1 << 20)

if data:

buf.append(data)

else: # EOF

break

elif p.poll() is not None: # process is done

assert not select([master_fd], [], [], 0)[0] # nothing to read

break

os.close(slave_fd)

os.close(master_fd)

print "".join(buf), p.returncode-128

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。