You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Bash脚本捕获被终止进程的状态码

捕获后台运行进程的退出码问题

编辑:感谢各位的帮助,我用于解决问题的代码已放在文末(*);另外,关于执行命令的输出,考虑到byeprogram会向stdout输出内容,我尝试将其重定向到管道,但效果不佳。

我在项目开发中遇到一个问题:无法捕获后台运行进程的退出码(status code)。以下面的程序为例,该进程在收到SIGINT信号时会以99作为退出码退出,代码如下:

#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

void bye(){
// 收到SIGINT信号时以99为退出码退出
    exit(99);
}
int main(int argc,char** argv){
    signal(SIGINT, bye);
    while(1){
        sleep(1);
    }
    return 0;
}

编译该程序的命令:

gcc example.c -o byeprogram

同一目录下的Bash脚本如下:

set -x

__do_before_wait(){
    ## 一些命令
    return 0
}


__do_after_trap(){
    ## 一些命令
    return 0
}

runbg() {
    local __start_time __finish_time __run_time
    __start_time=$(date +%s.%N)

    # 在后台运行命令
    ($@) &
    __pid=$!

    trap '
        kill -2 $__pid
        echo $?
        __finish_time=$(date +%s.%N)
        __run_time=$(echo "$__finish_time - $__start_time" | bc -l)
        echo "$__run_time"
        __do_after_trap || exit 2
    ' SIGINT
    __do_before_wait || exit 1
    wait $__pid
    ## 现在按下ctrl+c会执行trap中定义的命令
}

out=`runbg  /path/to/byeprogram`

我的问题是:我想要捕获或输出99这个状态码,但目前无法实现。我曾直接在终端执行byeprogram并按下Ctrl+C,此时它会返回99,请问如何在Bash脚本中捕获这个99状态码?


解决方案

runbg() {
# 输出格式:status_code,run_time
# 获取状态码:| gawk -F, '{print $1}'
# 获取运行时间:| gawk -F, '{print $2}'

    __trap_code(){
        kill -2 $__pid
        wait $__pid
        __status_code=$?
        __finish_time=$(date +%s.%N)
        __run_time=$(echo "$__finish_time - $__start_time" | bc -l)
        echo "$__status_code,$__run_time"
        __do_after_trap
        exit 0
    }
    local __start_time __finish_time __run_time
    __start_time=$(date +%s.%N)
    ($@) &
    local __pid=$!
    trap __trap_code SIGINT
    __do_before_wait
    wait $pid
    __status_code=$?
    __finish_time=$(date +%s.%N)
    __run_time=$(echo "$__finish_time - $__start_time" | bc -l)
    echo "$__status_code,$__run_time"
}

内容的提问来源于stack exchange,提问作者Amr Alasmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 21:53:27