我在终止bash脚本中的进程执行时遇到问题。
基本上,我的脚本执行以下操作:
CTRL+C
停止的程序我的问题是,当我命中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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句