问题描述
我想从 bash
启动后台进程,以便随后可以向其发送SIGINT信号(例如:通过 kill
或 htop
)。我该怎么做?
I want to launch a background process from bash
in such a way that I can then send SIGINT signals to it (eg: via kill
or htop
). How do I do that?
默认情况下,在后台启动进程时, SIGINT
和 SIGQUIT
被忽略(请参阅)。
By default, when a process is launched in the backround, SIGINT
and SIGQUIT
are ignored (see this question).
推荐答案
如果执行了该过程(不仅是子shell,而是基于二进制文件),则可以通过包装程序运行该程序,该包装程序将撤消SIGINT / SIGQUIT忽略:
If the process is execed (=isn't just a subshell but is based on binary), you can run it through a wrapper that'll undo the SIGINT/SIGQUIT ignore:
reset_sigint.c:
reset_sigint.c:
#include <signal.h>
#include <unistd.h>
int main(int C, char**V)
{
sigaction(SIGINT,&(struct sigaction){.sa_handler=SIG_DFL}, 0);
execvp(V[1],V+1);
return 127;
}
为防止SIGINT / SIGQUIT,更一般地忽略作为命令运行的任何进程在外壳中,您可以使用 set -m
在
To prevent the SIGINT/SIGQUIT ignore more generically for any process run as a command in the shell, you can run it with set -m
on
sh -c 'set -m; ( sleep 10 )& ps -p $! -o ignored'
#compare with: sh -c '( sleep 10 )& ps -p $! -o ignored'
,但这会在一个单独的进程组中将命令作为(可能是不希望的)副作用。
but that'll run the command in a separate process group as a (possibly undesirable) sideffect.
这篇关于我该如何通过将取消SIGINT忽略的包装程序启动后台进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!