3
1
Have a script as below:
#!/bin/bash
#
# run this script. don't run it if it's already running.
#
PIDFILE=/tmp/script.pid
LOGFILE=script.log
if [[ -f $PIDFILE ]]; then
echo "$PIDFILE exists. Not going to run..."
exit 0
fi
sleep 10m >> $LOGFILE 2>&1 &
PID=$!
echo $PID > $PIDFILE
trap "echo Exiting...; rm $PIDFILE; exit $?" INT TERM EXIT KILL
wait $PID
Am invoking this script as below:
timeout 2m ./test_script
On timeout or ctrl+c, the script prints "Exiting" twice.
# timeout 2m ./test_script
^CExiting...
Exiting...
rm: cannot remove `/tmp/script.pid': No such file or directory
Below is the output of strace and more data:
# ps -ef | grep -v grep | egrep -i "sleep|time"
root 8571 4690 0 12:17 pts/0 00:00:00 timeout 2m ./test_script
root 8572 8571 0 12:17 pts/0 00:00:00 /bin/bash ./test_script
root 8573 8572 0 12:17 pts/0 00:00:00 sleep 10m
# cat /tmp/script.pid
8573
# strace -p 8571
Process 8571 attached - interrupt to quit
wait4(-1, 0x7fffc43fad4c, 0, NULL) = ? ERESTARTSYS (To be restarted)
--- SIGINT (Interrupt) @ 0 (0) ---
kill(0, SIGINT) = 0
kill(0, SIGCONT) = 0
--- SIGCONT (Continued) @ 0 (0) ---
rt_sigreturn(0) = 61
--- SIGINT (Interrupt) @ 0 (0) ---
rt_sigreturn(0x2) = 61
wait4(-1, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 8572
--- SIGCHLD (Child exited) @ 0 (0) ---
close(1) = 0
close(2) = 0
exit_group(0) = ?
Process 8571 detached
Can someone kindly assist me with understanding the internals on why the script traps the signal twice to print "Exiting..." 2 times ?
rm: cannot remove /tmp/script.pid: No such file or directory
<-- you're executingecho "Exiting..."
twice, are you sure you need all ofINT TERM EXIT KILL
- might it be that two of them get triggered - at the same time - when you hit CTRL-C? – Hannu – 2015-05-03T19:51:09.967that is probably what is happening. two signals being handled almost simultaneously by
trap
. As far as the script needing to trap-on all the 4 signals specified, yes I need them all. As an alternative, I am simply using the timeout from within my script. This gets around the problem of double invocation whentimeout
completes – cog_n1t1v3 – 2015-05-03T21:51:57.117You cannot catch
KILL
, so that one does not count. If I run your script using bash 4.1.5 however, I am seeing only one message forTERM
(when it does exit) and no exit forINT
. Perhaps the version of bash matters. – Thomas Dickey – 2015-05-04T10:31:58.840