【问题标题】:How do I launch a background process through a wrapper that'll undo the SIGINT ignore?如何通过将撤消 SIGINT 忽略的包装器启动后台进程?
【发布时间】:2018-03-08 17:01:09
【问题描述】:

我想从bash 启动一个后台进程,这样我就可以向它发送SIGINT 信号(例如:通过killhtop)。我该怎么做?

默认情况下,当一个进程在后台启动时,SIGINTSIGQUIT 会被忽略(参见this question)。

【问题讨论】:

  • 你现在编码了什么?

标签: linux bash command-line


【解决方案1】:

如果进程被执行(=不仅仅是一个子shell,而是基于二进制文件),您可以通过一个包装器运行它,该包装器将撤消 SIGINT/SIGQUIT 忽略:

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 更普遍地忽略在 shell 中作为命令运行的任何进程,您可以使用 set -m on 运行它

sh -c 'set -m; ( sleep 10 )& ps -p $! -o ignored'
#compare with: sh -c '( sleep 10 )& ps -p $! -o ignored'

但这会在单独的进程组中运行命令,作为(可能不受欢迎的)副作用。

【讨论】:

  • 奇怪的是,我没有设法让第二个选项为我工作。不知道为什么 - 我在后台运行另一个 bash 脚本的 bash 脚本。 bg 脚本正在启动一个 python 程序。我在第二个 bash 脚本中尝试了set -m,但 python 仍然没有得到 SIGINT。最后,正如here 所建议的那样,只需在 Python 中添加一个引发 KeyboardInterrupt 的 SIGINT 处理程序就可以了。
  • 试试bash -c ' python -c "import time; time.sleep(100)" &amp; ps -o ignored $!'bash -c ' set -m ; python -c "import time; time.sleep(100)" &amp; ps -o ignored $!'。这个对我有用。第二个掩码不再以 6 (==1
  • 好的,现在我很困惑!一组简单的脚本模拟我的真实脚本,第一个是set -m(在 bg 中调用第二个 bash 脚本,调用 python),python 得到 SIGINT!也许我只在第二个脚本中尝试了set -m??当我有一点时间时,我可能会再看一下我的生产脚本,看看是否还有其他可能令人困惑的事情?目前,我已经接受了你的回答(:谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-08
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-12
  • 2010-12-03
相关资源
最近更新 更多