[英]Terminate a process started by a bash script with CTRL-C
I'm having an issue with terminating the execution of a process inside a bash script. 我遇到了在bash脚本中终止进程执行的问题。
Basically my script does the following actions: 基本上我的脚本执行以下操作:
CTRL+C
to stop CTRL+C
停止的程序 My problem is that when I hit CTRL+C
the whole script terminates, not just the "inner" program. 我的问题是,当我按下
CTRL+C
,整个脚本终止,而不仅仅是“内部”程序。
I've seen around some scripts that do this, this is why I think it's possible. 我已经看到一些脚本执行此操作,这就是为什么我认为这是可能的。
Thanks in advance! 提前致谢!
You can set up a signal handler using trap
: 您可以使用
trap
设置信号处理程序:
trap 'myFunction arg1 arg2 ...' SIGINT;
I suggest keeping your script abortable overall, which you can do by using a simple boolean: 我建议保持你的脚本整体可用,你可以使用一个简单的布尔值来做:
#!/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...
In order to reduce the likelihood of messing up with allowAbort
, or just to keep it a bit cleaner, you can define a wrapper function to do the job for you: 为了减少搞乱
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.