假设我正在运行以下示例保存为 hello.sh
,
#!/bin/bash
hello() {
echo "hello"
}
trap "hello" INT
sleep 100
echo "end"
而在Shell I开始 Hello.sh
。 1秒钟后,我按 ctrl-c
。
请将睡眠
视为我开始的任何长期过程。
这是我的问题:
- 当生成
sigint
时,它是直接传递到 Sleep
还是直接发送给Shell脚本?
- 如果是第二个,我可以让
睡眠
有机会处理 sigint
,并且不传播其父 hello.shy.sh
吗?
- 如果是第一个,
睡眠
的状态是什么?
我的测试使我觉得以下发生在
睡眠
开始运行
hello.sh
接收到信号
- 函数
Hello
开始运行
- 函数
> Hello
完成
echo“ end”
开始运行
- 脚本退出。
但是在哪个阶段,睡眠
过程退出,并且由于什么(例如Sigint停止了 Sleep
过程?)
Suppose I am running the following example saved as hello.sh
#!/bin/bash
hello() {
echo "hello"
}
trap "hello" INT
sleep 100
echo "end"
and in shell I start hello.sh
. After 1 second I press Ctrl-C
.
Please treat sleep
as any long-run process that I started.
Here are my questions:
- When
SIGINT
is generated, is it delivered to sleep
directly or to the shell script?
- If it is the second, can I let
sleep
has a chance to handle the SIGINT
and do not propagate to its parent hello.sh
?
- If it is the first, what is the status of
sleep
after the hello
function is finished?
My tests made me feel that the following occurred in order
sleep
started to run
hello.sh
received the signal
- function
hello
started to run
- function
hello
finished
echo "end"
started to run
- the script exits.
But at which stage the sleep
process exits and because of what (e.g. the SIGINT stopped the sleep
process?)
发布评论
评论(1)
一些解释:
sleep
作为bash
的子进程运行。bash
和sleep
在同一个进程组中运行,该进程组现在是前台进程组。当按下CTRT-C时,它将生成
SIGINT
,并且该信号将发送到中的所有进程前台进程组,因此bash
和sleep
都会收到SIGINT
。根据bash 手册 (可以另请参阅
man bash
)<块引用>
如果 bash 正在等待命令完成并接收到已设置陷阱的信号,则陷阱将不会执行直到命令完成。
所以这里
bash
会等待sleep
被杀死(默认的SIGINT行为是终止进程。请参阅signal(7)) 首先,然后bash
运行它的SIGINT
陷阱。根据 bash 手册
<块引用>
简单命令的返回值是其退出状态,如果命令由信号
n
终止,则为128+n
。SIGINT
为 2 (请参阅kill -l
),因此sleep
的退出状态为128+2=130
。Some explanation:
sleep
runs as a child process ofbash
.bash
andsleep
are running in the same process group which is now the foreground process group.When CTRT-C is pressed, it'll generate
SIGINT
and the signal will be sent to all processes in the foreground process group so bothbash
andsleep
will receiveSIGINT
.According to bash manual (can also see
man bash
)So here
bash
would wait forsleep
to be killed (The default SIGINT behavior is to terminate the process. See signal(7)) first and thenbash
runs itsSIGINT
trap.According to bash manaul
The
SIGINT
is 2 (seekill -l
) sosleep
's exit status is128+2=130
.