Tomek
Tomek

Reputation: 641

Bash: handle signals asynchronously (no background task)

Is it possible to asynchronously handle signals in Bash?

I know about the trap command. The way it works is that it waits for the current command to finish before handling the signal. The only way to handle the signal at the time when it arrives is to run the current command in background.

Lets assume we cannot run our command in background (e.g. because we want to be able to have a keyboard input via stdin), is there a way to handle signals when they are delivered to the script?

Upvotes: 1

Views: 66

Answers (1)

JB.
JB.

Reputation: 42094

It's not possible to handle signals synchroneously if the script isn't in the foreground. The bash manpage is pretty clear in this regard:

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.

Depending on your actual case, it might be possible to work around that by having your signals delivered to a background subprocess, or by keeping the script in the foreground and routing input to your command. Both are pretty contrived.

Upvotes: 1

Related Questions