今天,我遇到了一个问题,由Shell脚本启动的程序无法接收INT信号.经过一番调查,我将在下面显示我的发现.
这是我要运行的目标程序,我使用gcc hello.c -o hello.out进行编译.如果您手动启动该程序,则可以通过kill -2来停止它.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
while (1) {
printf("--------Hello Wolrd!\n");
sleep(2);
}
return 0;
}
然后,我有一个Shell脚本,该脚本在启动程序之前会进行一些处理.这是简洁的版本,我们将其称为trap.sh:
#!/bin/bash
pid=0
function singal_handler() {
echo "pid is "$java_pid
}
trap "singal_handler" INT
pid=2
nohup ./hello.out &
while true; do
echo "running...."
sleep 2
done
注意,我使用trap捕获INT信号来完成自己的工作,并使用nohup启动hello.out.
现在,我通过bash trap.sh启动程序.
通过向我的trap.sh发出kill -2,可以预期该行为,即pid输出消失了.
令我惊讶的是,这时,当我向后台发出kill -2 hello.out时,hello.out仍然存在,但不会消失.
所以我写这个问题来问为什么会发生这种情况. bash陷阱会覆盖其子命令的信号处理程序吗?
我的平台是64位linux:
uname -r —–> 3.10.0-123.el7.x86_64
谢谢.
解决方法:
When a simple command other than a builtin or shell function is to be executed, it is invoked in a separate execution environment that consists of the following. Unless otherwise noted, the values are inherited from the shell.
- the shell’s open files, plus any modifications and additions specified by redirections to the command
- the current working directory
- the file creation mode mask
- shell variables and functions marked for export, along with variables exported for the command, passed in the environment (see Environment)
- traps caught by the shell are reset to the values inherited from the shell’s parent, and traps ignored by the shell are ignored
A child created via fork(2) inherits a copy of its parent’s signal dispositions. During an execve(2), the dispositions of handled signals are reset to the
default; the dispositions of ignored signals are left unchanged.
所以是的,SIGINT get被忽略了,因为父外壳将忽略它.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。