【发布时间】:2022-01-04 10:59:21
【问题描述】:
我发现如果我有类似的东西:
#!/usr/bin/env bash
function abort-politely {
echo 'Aborting politely'
{
sleep 5
touch .stop
}
}
trap 'abort-politely' SIGINT
{
while [ ! -r .stop ] ; do echo hello world ; sleep 1 ; done
rm -f .stop
} &
wait $!
echo Exiting
它的行为和我预期的一样,也就是说后台任务在中断后会持续5s:
hello world
hello world
hello world
hello world
<Ctrl+C pressed>
Aborting politely
hello world
hello world
hello world
hello world
hello world
Exiting
但是,如果我将 process substitution 作为后台进程的一部分引入...
#!/usr/bin/env bash
function abort-politely {
echo 'Aborting politely'
{
sleep 5
touch .stop
}
}
trap 'abort-politely' SIGINT
{
# The "while" loop below is all that has changed
while [ ! -r .stop ] && read line; do echo hello $line ; done < <(
while : ; do echo world ; sleep 1 ; done
)
rm -f .stop
} &
wait $!
echo Exiting
...当按下 Ctrl+C 时,后台进程似乎立即退出:
hello world
hello world
hello world
hello world
<Ctrl+C pressed>
Aborting politely
<5 seconds delay>
Exiting
我期待与第一种情况相同的输出。
这怎么不像我预期的那样工作?有没有办法让它像我希望的那样表现?我想我需要的是进程替换继续进行,直到不再被读取。 (我想知道在进程替换块中添加trap '' SIGINT 是否可能是解决方案,但它会立即退出。)
【问题讨论】: