1

In Bash 5 I ran into a situation where I want to do the following:

trap 'echo trapped!' USR1
while true; do kill -SIGUSR1 $$; sleep 1; done &

But I have to press enter on keyboard every time the signal is sent to make the trap code continue.

Actually I expect the trap to be executed without any keyboard interaction.

EDIT:

Finally I got it working like this:

trap 'echo trapped!' USR1
while true; do kill -USR1 $$; kill -INT $$; sleep 1; done &

But I consider the solution as workaround and not as answer.

3

Someone seems to have a very similar problem here.
Long story short if it's OK to execute the command from the trap built-in in a subprocess ('echo trapped!' in this case). You can put your commands in a file (for example a.sh):

trap 'echo trapped!' USR1
while true; do kill -USR1 $$; sleep 1; done

and execute the file as a background process with bash a.sh &
If it's not okay to do it in a subprocess there is no good solution since the interactive shell does a blocking read operation while waiting for the user to enter a command and it doesn't handle most signals while that is happening (as you have noticed it does handle SIGINT). The solution above works since the trap is in a non-interactive shell (thus it is not in the middle of a blocking read when it gets the signal).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.