【发布时间】:2021-09-22 06:46:01
【问题描述】:
在 python 中,我的应用程序需要使用 subprocess 等模块创建子进程。通常,这些子进程是使用 ASAN (Address Sanitizer) 强化的 C/C++ 程序。
我希望能够检测子进程是否因 asan 错误而崩溃,并且仍然能够收集 asan 报告。
有没有办法做到这一点?
【问题讨论】:
标签: python debugging subprocess address-sanitizer
在 python 中,我的应用程序需要使用 subprocess 等模块创建子进程。通常,这些子进程是使用 ASAN (Address Sanitizer) 强化的 C/C++ 程序。
我希望能够检测子进程是否因 asan 错误而崩溃,并且仍然能够收集 asan 报告。
有没有办法做到这一点?
【问题讨论】:
标签: python debugging subprocess address-sanitizer
子进程模块具有捕获标准输出和标准错误的设施。文档很有帮助:https://docs.python.org/3/library/subprocess.html
例如,您可以这样做:
import subprocess
import sys
try:
subprocess.run(["my_program", "--flag", "my_param", input, output],
check=True, stderr=subprocess.PIPE)
except subprocess.CalledProcessError as err:
# You can now query stderr with err.stderr and do what you want with it:
# printing, saving etc. for example:
if "address_sanitizer" in err.stderr:
print(err.stderr, file=sys.stderr)
raise err # Raise the error to make you program crash if desired
您也可以不使用check=True 运行程序。
import subprocess
import sys
program_result= subprocess.run(["my_program", "--flag", "my_param", input, output],
stderr=subprocess.PIPE)
if program_result.return_code != 0:
print(program_result.stderr, file=sys.stderr)
program_result.check_output() # This will raise an error
【讨论】:
如果子进程由于 Asan 发现的错误而中止,它们会将详细的错误消息打印到 stderr。然后,您的根应用程序可以检测到以非零退出代码终止的子进程并打印它的标准错误以供检查。
或者,您可以要求 Asan 通过以下方式将错误报告存储在文件系统中
# Error reports will be saved to path/to/asan/logs/asan.PID files
$ export ASAN_OPTIONS=log_path=path/to/asan/logs/asan
$ ./main.py
【讨论】:
ASAN_OPTIONS=log_path=path/to/asan/logs/asan 吗? @yugr