0

The following script in Linux prints "sleep 1 finished", but in general POSIX you can not use sleep 0.1, since the argument has to be integer. If I leave the command out, the script will never exit (why!?), but takes very much CPU power. If I replace it by ( : ) it works in my system, but I am not sure, if it will in general, and even that takes a lot of CPU power. What is a better POSIX solution?

#!/bin/sh

sleep 2 &
pid=$!
sleep 1 &
pid_sleep=$!
while kill -0 "$pid" 2>/dev/null; do
    kill -0 "$pid_sleep" 2>/dev/null || {
        echo sleep 1 finished
        exit 0
    }
    sleep 0.1
done
2

An alternative to wait for the sleep to exit would be with the wait command:

sleep 2 &
pid=$!
sleep 1 &
pid_sleep=$!

wait $pid $pid_sleep
echo "commands finished"
  • Yes, but I need to know which command finished first, and it is enough that one of them finishes. – jarno Aug 3 '17 at 6:31

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.