[英]stop currently running bash script lazily/gracefully
Say I have a bash script like this:假设我有一个这样的 bash 脚本:
#!/bin/bash
exec-program zero
exec-program one
the script issued a run command to exec-program with the arg "zero", right?脚本向 exec-program 发出了一个运行命令,参数为“零”,对吗? say, for instance, the first line is currently running.
例如,第一行当前正在运行。 I know that Ctrl-C will halt the process and discontinue executing the remainder of the script.
我知道 Ctrl-C 将停止进程并停止执行脚本的其余部分。
Instead, is there a keypress that will allow the current-line to finish executing and then discontinue the script execution (not execute "exec-program one") (without modifying the script directly)?相反,是否有一个按键可以让当前行完成执行然后停止脚本执行(不执行“exec-program one”)(不直接修改脚本)? In this example it would continue running "exec-program zero" but after would return to the shell rather than immediately halting "exec-program zero"
在这个例子中,它会继续运行“exec-program zero”,但之后会返回到shell而不是立即停止“exec-program zero”
TL;DR Something runtime similar to "Ctrl-C" but more lazy/graceful ?? TL;DR 运行时类似于“Ctrl-C”但更懒惰/优雅??
In the man page, under SIGNALS section it reads:在手册页的 SIGNALS 部分下,它写道:
If bash is waiting for a command to complete and receives a signal for which a trap has been set, the trap will not be executed until the command completes.
如果 bash 正在等待命令完成并接收到设置了陷阱的信号,则在命令完成之前不会执行陷阱。
This is exactly what you're asking for.这正是你要问的。 You need to set an exit trap for SIGINT, then run
exec-program
in a subshell where SIGINT is ignored;您需要为 SIGINT 设置退出陷阱,然后在忽略 SIGINT 的子 shell 中运行
exec-program
; so that it'll inherit the SIG_IGN handler and Ctrl+C won't kill it.这样它就会继承 SIG_IGN 处理程序并且Ctrl+C不会杀死它。 Below is an implementation of this concept.
下面是这个概念的一个实现。
#!/bin/bash -
trap exit INT
foo() (
trap '' INT
exec "$@"
)
foo sleep 5
echo alive
If you hit Ctrl+C while sleep 5
is running, bash will wait for it to complete and then exit;如果在
sleep 5
运行时按 Ctrl+C ,bash 将等待它完成然后退出; you will not see alive
on the terminal.你不会在终端上看到
alive
。
exec
is for avoiding another fork() btw. exec
是为了避免另一个 fork() 顺便说一句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.