簡體   English   中英

使用CTRL-C終止由bash腳本啟動的進程

[英]Terminate a process started by a bash script with CTRL-C

我遇到了在bash腳本中終止進程執行的問題。

基本上我的腳本執行以下操作:

  1. 發出一些啟動命令
  2. 啟動等待CTRL+C停止的程序
  3. 對程序檢索的數據進行一些后處理

我的問題是,當我按下CTRL+C ,整個腳本終止,而不僅僅是“內部”程序。

我已經看到一些腳本執行此操作,這就是為什么我認為這是可能的。

提前致謝!

您可以使用trap設置信號處理程序:

trap 'myFunction arg1 arg2 ...' SIGINT;

我建議保持你的腳本整體可用,你可以使用一個簡單的布爾值來做:

#!/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...

為了減少搞亂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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM