[英]bash trap won't ignore signal
Please consider this bash-script: 请考虑这个bash脚本:
#!/bin/bash
trap '' INT
echo sleep:
sleep 5
echo rsync:
rsync -a /usr/lib /var/tmp
Trying to interrupt sleep with ctrl-c fails, as expected. 正如预期的那样,尝试使用ctrl-c中断睡眠失败。 But rsync is interruptible (the order of sleep & rsync doesn't matter)?
但rsync是可中断的(睡眠和rsync的顺序无关紧要)? Any ideas are welcome!
欢迎任何想法!
Edit: Found a difference: rsync itself starts 2 child procs (client/server, which produce the 2 error msgs, i assume), and these seem not to inherit the 'ignorance' of its parent. 编辑:发现一个区别:rsync本身启动2个子进程(客户端/服务器,产生2个错误消息,我假设),这些似乎不会继承其父级的“无知”。 Must dive into bash sources and find out how trap is working...
必须潜入bash源并找出陷阱如何工作......
您是否尝试过将rsync
与--no-detach
一起使用,如SO问题bash
所建议的那样, 在rsync
subshell / exec语句中没有捕获中断 ?
It's pretty clear from experimentation that rsync
behaves like other tools such as ping
and do not inherit signals from the calling Bash parent. 从实验中可以清楚地看出,
rsync
行为与其他工具(如ping
并且不会从调用Bash父级继承信号。
So you have to get a little creative with this and do something like the following: 因此,你必须对此有一点创意,并执行以下操作:
$ cat rsync.bash
#!/bin/sh
set -m
trap '' SIGINT SIGTERM EXIT
rsync -avz LargeTestFile.500M root@host.mydom.com:/tmp/. &
wait
echo FIN
Now when I run it: 现在当我运行它:
$ ./rsync.bash
X11 forwarding request failed
building file list ... done
LargeTestFile.500M
^C^C^C^C^C^C^C^C^C^C
sent 509984 bytes received 42 bytes 92732.00 bytes/sec
total size is 524288000 speedup is 1027.96
FIN
And we can see the file did fully transfer: 我们可以看到文件完全转移:
$ ll -h | grep Large
-rw-------. 1 501 games 500M Jul 9 21:44 LargeTestFile.500M
The trick here is we're telling Bash via set -m
to disable job controls on any background jobs within it. 这里的诀窍是我们通过
set -m
告诉Bash在其中的任何后台作业上禁用作业控制。 We're then backgrounding the rsync
and then running a wait
command which will wait on the last run command, rsync
, until it's complete. 然后,我们将后台运行
rsync
,然后运行wait
命令,该命令将等待最后一次运行命令rsync
,直到它完成。
We then guard the entire script with the trap '' SIGINT SIGTERM EXIT
. 然后我们用
trap '' SIGINT SIGTERM EXIT
保护整个脚本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.