bash rsync is Killed by signal 2
I'm trying to prevent the user from cancelling the script by using ctrl + c. The following script executes completely, except rsync
that insists on dying, displaying the error Killed by signal 2
.
Is it possible to avoid rsync
from dying? If so, can I put it in the background, or should it be in the foreground?
script:
trap '' SIGINT SIGTERM SIGQUIT
cd /tmp
nohup rsync -e 'ssh -o LogLevel=ERROR' -av --timeout=10 --delete-excluded myapp.war myserver:/tmp/ < /dev/null > /tmp/teste 2> /tmp/teste2
let index=0
while [ $index -lt 400000 ]
do
let index=index+1
done
echo "script finished"
echo "index:$index"
I'm suspecting that the ssh channel is dying before rsync
. Following the end of the output of the strace
command in pid of rsync
:
[...]
write(4, "\374\17\0\7", 4) = 4
select(5, NULL, [4], [4], {10, 0}) = 1 (out [4], left {9, 999998})
--- SIGINT (Interrupt) @ 0 (0) ---
--- SIGCHLD (Child exited) @ 0 (0) ---
wait4(-1, [{WIFEXITED(s) && WEXITSTATUS(s) == 255}], WNOHANG, NULL) = 12738
wait4(-1, 0x7fffaea6a85c, WNOHANG, NULL) = -1 ECHILD (No child processes)
rt_sigreturn(0xffffffffffffffff) = 0
select(0, NULL, NULL, NULL, {0, 400000}) = 0 (Timeout)
rt_sigaction(SIGUSR1, {SIG_IGN, [], SA_RESTORER, 0x3fcb6326b0}, NULL, 8) = 0
rt_sigaction(SIGUSR2, {SIG_IGN, [], SA_RESTORER, 0x3fcb6326b0}, NULL, 8) = 0
wait4(12738, 0x7fffaea6aa7c, WNOHANG, NULL) = -1 ECHILD (No child processes)
getpid() = 12737
kill(12738, SIGUSR1) = -1 ESRCH (No such process)
write(2, "rsync error: unexplained error ("..., 72) = 72
write(2, "\n", 1) = 1
exit_group(255) = ?
Process 12737 detached
Solution 1:
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 [email protected]:/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