A
A
Alexey Zhurbitsky2011-06-08 10:47:17
linux
Alexey Zhurbitsky, 2011-06-08 10:47:17

Bash, trap signal?

There is a simple script

#!/bin/bash

trap 'echo Catched' TERM

echo $$

#cat /dev/zero | 
while true ; do
    sleep 1
done

Everything works - after running the script, I send it a signal TERM
kill -TERM [PID]
trap catches this signal and displays "Catched".
However, if you uncomment the line,
cat /dev/zero |
then trap does not catch anything and does not complete the script, i.e. absolutely nothing happens.
Actually the question is - is it possible to catch a signal inside such a bash script? If yes, then how?
UPD. Decision
#!/bin/bash

trap 'echo Catched' TERM

echo $$

cat /dev/zero | 
while true ; do
    sleep 1
done &

while : ; do
    wait $!
done

Answer the question

In order to leave comments, you need to log in

3 answer(s)
@
@sledopit, 2011-06-08
@blo

bash man:

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.

In theory, wait can save you.

S
shadowalone, 2011-06-08
@shadowalone

Have you tried another command that does not hang pending like
cat /dev/zero |
?

M
Maxim, 2012-10-15
@Speakus

I think this is your case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question