gpt4 book ai didi

bash - 如何写入进程 ID 并获取倒数第二个命令的退出代码

转载 作者:行者123 更新时间:2023-11-29 09:46:15 25 4
gpt4 key购买 nike

我想运行一个命令,在命令启动时立即将进程 ID 写入文件,然后获取命令的退出状态。这意味着,虽然进程 ID 必须立即写入,但我只希望在初始命令完成时退出状态。

不幸的是,以下语句将运行命令,立即写入进程 ID 但不会等待命令完成。此外,我只会获得 echo 命令的退出状态,而不是初始命令的退出状态

command 在我的例子中是 rdiff-backup。

我需要如何修改语句?

<command> & echo $! > "/pid_file"
RESULT=$?
if [ "$RESULT" -ne "0" ]; then
echo "Finished with errors"
fi

最佳答案

您需要在后台进程上等待以获取其退出状态:

_command_for_background_ & echo $! > pid_file
: ... do other things, if any ...
#
# it is better to grab $? on the same line to prevent any
# future modifications inadvertently breaking the strict sequence
#
wait $(< pid_file); child_status=$?
if [[ $child_status != 0 ]]; then
echo "Finished with errors"
fi

关于bash - 如何写入进程 ID 并获取倒数第二个命令的退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41975048/

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