当我将作业控制启用到shell脚本(使用set -m
)时,我不再能够捕获进程信号。看看下面的代码:
#!/bin/bash
set -m
for i in `seq 15`; do
trap 'echo " Signal $i catched"' $i
done
while true; do
echo " Waiting for a process signal"
sleep 999
done
当我运行上面的代码并按Ctrl + C时,没有任何反应:
Waiting for a process signal
^CWaiting for a process signal
但是,当我运行删除set -m
的相同代码时,我得到了答案:
Waiting for a process signal
^C Signal 15 catched
我的问题是:
注意:所有流程都不会发生,如果我使用read
代替sleep
,它确实有效。
答案 0 :(得分:3)
解决方案是将睡眠置于后台并使用内置的bash wait
等待睡眠完成时等待。因此,试试这个:
#!/bin/bash
set -m
for i in `seq 15`; do
trap 'echo " Signal $i catched"' $i
done
while true; do
echo " Waiting for a process signal"
sleep 999 & wait $!
done
示例运行:
$ bash script
Waiting for a process signal
^C Signal 15 catched
Waiting for a process signal
^C Signal 15 catched
Waiting for a process signal
有关详细信息,请参阅Greg's FAQ。