Can anybody tell why there the difference is?
Ctrl+C gets to sleep
as well, while kill <pid>
doesn't. In effect the latter way needs sleep
to exit by itself before hi!
is printed. What you call "1 second delay" is about 1 second at most and about 0.5 on average (it may take longer if the OS is very busy with other tasks).
You can clearly see the difference by using
pv -qL 1 <<< "0123456789"
instead of sleep 1
.
Note that
kill -- -<pid> # note the minus sign before PID
would send the signal to the entire process group, so to sleep
(or pv
) as well.
Is there a way that always trigger trap command immediately no matter what is going on?
There is this question How to handle signals in bash during synchronous execution?
From one of the answers:
If bash is waiting for a command to complete and receives a signal for which a trap has been set, the trap will not be executed until the command completes. When bash is waiting for an asynchronous command via the wait
builtin, the reception of a signal for which a trap has been set will cause the wait
builtin to return immediately with an exit status greater than 128, immediately after which the trap is executed.
So, run your external program asynchronously and use wait
. Kill it using $!
.
In your case this method leads to the following quick and dirty script:
#!/bin/bash
trap 'kill "$!"; echo hi!' SIGINT SIGTERM
echo "pid is $$"
while true; do
sleep 1 &
wait
done