vera
vera

Reputation: 138

signal trap induces next command execution in bash

Following Interrupt sleep in bash with a signal trap, I run the code :

trap "echo 'Doing something'" SIGUSR1

echo "$$" > .daemon.pid
while true
do
    echo "in loop"
    sleep 60 &
    wait $!
done

The signal trap works, but daemon then goes to the next iteration of the infinite while loop, even if the sleep has not ended.

I then modify the while loop inner code as following (addition of a second wait command) :

while true
do
    echo "in loop"
    sleep 60 &
    wait $!
    wait $!
done

In that case I am able to send 2 trap commands before the daemon goes to the next iteration, still even if the sleep as not ended.

Is it possible to enforce that the daemon resume the sleep after trap such that it does not go to next iteration before the end of the sleep execution, regardless of the number of signals sent ?

EDIT: Ugly answer

I have found an ugly answer. I am still awaiting a better answer that might less ugly :) for the charm of code...

while :
do
    echo "in loop"
    sleep 60 &
    while ! wait $!
    do
        continue
    done
done

Upvotes: 2

Views: 219

Answers (1)

Armali
Armali

Reputation: 19375

Is it possible to enforce that the daemon resume the sleep after trap …

Actually, the sleep can't be resumed, since it is not even interrupted - only wait is.

I am still awaiting a better answer that might less ugly …

As uglyness is a matter of taste, less ugly than

    while ! wait $!
    do
        continue
    done

one might find

    until wait $!; do :; done

or just

    until wait; do :; done

(if there's no other currently active child process).

Upvotes: 1

Related Questions