bash trap won't ignore signal

左心房为你撑大大i 提交于 2021-01-23 04:57:40

问题


Please consider this bash-script:

#!/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. But rsync is interruptible (the order of sleep & rsync doesn't matter)? 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. Must dive into bash sources and find out how trap is working...


回答1:


Have you tried using rsync with --no-detach as advised in the SO question bash not trapping interrupts during rsync subshell/exec statements?




回答2:


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.

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

How it works

The trick here is we're telling Bash via set -m to disable job controls on any background jobs within it. 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.

We then guard the entire script with the trap '' SIGINT SIGTERM EXIT.

References

  • https://access.redhat.com/solutions/360713
  • https://access.redhat.com/solutions/1539283
  • Delay termination of script


来源:https://stackoverflow.com/questions/13570680/bash-trap-wont-ignore-signal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!