gpt4 book ai didi

c++ - 在 bash 中获取进程的退出状态

转载 作者:搜寻专家 更新时间:2023-10-31 00:10:44 26 4
gpt4 key购买 nike

我有一个名为 Test 的 C++ 可执行文件。我想在执行完成时找出 GetExitCodeProcess() 代码。

我可以通过在另一个包装程序中编写以下内容来找出状态代码:

...
int status = system("./Test");

然后检查 WIFSIGNALED/WIFSTOPPED 等状态。

但是,我可以通过编写bash 脚本从.Test 程序的PID 中获取退出状态代码,而不是编写包装程序吗?

编辑 是否在执行./Test 后在bash 中写入$ 给出解决方案以上问题?

编辑:总结是——当我从命令行运行可执行文件时,我(不是程序)如何获得退出状态?

最佳答案

您可以在执行命令/bash 后简单地执行一个echo $?,这将输出程序的退出代码。

每个命令都会返回一个退出状态(有时称为返回状态或退出代码)。一个成功的命令返回一个 0,而一个不成功的返回一个通常可以解释的非零值作为错误代码。行为良好的 UNIX 命令、程序和实用程序返回成功完成后的 0 退出代码,但也有一些异常(exception)。

# Non-zero exit status returned -- command failed to execute.
echo $?

echo

# Will return 113 to shell.
# To verify this, type "echo $?" after script terminates.
exit 113

# By convention, an 'exit 0' indicates success,
# while a non-zero exit value means an error or anomalous condition

或者,如果您希望识别后台进程/脚本的返回代码(以 nohup 启动或在后台运行 & 运算符),您可以获得进程的 pid/script 启动并等待它终止,然后获取退出代码。

# Some random number for the process-id is returned
./foo.sh &
[1] 28992

# Get process id of the background process
echo $!
28992

# Waits until the process determined by the number is complete
wait 28992

[1]+ Done ./foo.sh

# Prints the return code of the process
echo $?
0

另请查看 Bash Hackers Wiki - Exit Status

关于c++ - 在 bash 中获取进程的退出状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36837149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com