使用 CTRL-C 终止由 bash 脚本启动的进程

mag*_*n94 7 linux bash

我在终止 bash 脚本中的进程执行时遇到问题。

基本上我的脚本执行以下操作:

  1. 发出一些启动命令
  2. 启动一个等待CTRL+C停止的程序
  3. 对程序检索到的数据做一些后处理

我的问题是,当我点击CTRL+C整个脚本时终止,而不仅仅是“内部”程序。

我见过一些这样做的脚本,这就是为什么我认为这是可能的。

提前致谢!

Sig*_*uza 6

您可以使用以下命令设置信号处理程序trap

trap 'myFunction arg1 arg2 ...' SIGINT;
Run Code Online (Sandbox Code Playgroud)

我建议保持脚本整体可中止,您可以通过使用简单的布尔值来做到这一点:

#!/bin/bash

# define signal handler and its variable
allowAbort=true;
myInterruptHandler()
{
    if $allowAbort; then
        exit 1;
    fi;
}

# register signal handler
trap myInterruptHandler SIGINT;

# some commands...

# before calling the inner program,
# disable the abortability of the script
allowAbort=false;
# now call your program
./my-inner-program
# and now make the script abortable again
allowAbort=true;

# some more commands...
Run Code Online (Sandbox Code Playgroud)

为了减少搞乱 的可能性allowAbort,或者只是为了保持它更简洁,您可以定义一个包装函数来为您完成这项工作:

#!/bin/bash

# define signal handler and its variable
allowAbort=true;
myInterruptHandler()
{
    if $allowAbort; then
        exit 1;
    fi;
}

# register signal handler
trap myInterruptHandler SIGINT;

# wrapper
wrapInterruptable()
{
    # disable the abortability of the script
    allowAbort=false;
    # run the passed arguments 1:1
    "$@";
    # save the returned value
    local ret=$?;
    # make the script abortable again
    allowAbort=true;
    # and return
    return "$ret";
}

# call your program
wrapInterruptable ./my-inner-program
Run Code Online (Sandbox Code Playgroud)