1
I'm trying to write signal handlers in Bash scripts, testing under a Ubuntu 16.04 machine. Here I'm using the trap
command:
#!/bin/bash
trap "echo hi!" SIGINT SIGTERM
echo "pid is $$"
while true; do
sleep 1;
done
After running ./test.sh
, pressing Ctrl+C gives me immediate hi!
message under the current terminal. However, kill <pid>
under another terminal has a 1 second delay printing hi!
.
Can anybody tell why there the difference is? Is there a way that always trigger trap command immediately no matter what is going on? (like a sleep loop).
If we don't
kill "$!"
in trap, will we lost pid of the previoussleep 1
after reception of a signal? In another word, willwait
really return, or the OS just switches to execute signal handler then come back to wait later (looks like a return)? – dastan – 2019-02-15T02:55:20.677@dastan "then come back to
wait
later" -- I thinkwait
is no more. Why won't you test it? You can save the pid to a separate variable if you're afraid you can lose it. – Kamil Maciorowski – 2019-02-15T06:06:58.673