Skip to content

Conversation

@pdewilde
Copy link

The current implementation of safe_sleep.sh is a busy wait.

This seems to exist because sleep is not a shell builtin, and it can't be assumed all environments have the sleep binary.

Bash 4 and above support the builtin read command, which can be used as a sleep with the timeout feature. This pattern is described here:
https://github.com/dylanaraps/pure-bash-bible?tab=readme-ov-file#use-read-as-an-alternative-to-the-sleep-command

Despite Bash 4 shipping 16 years ago, bash 3.x is still the default shipped on MacOS due to 4+ being licensed as GPL3, so the busy wait was retained as a fallback.

Also the condition in the busy wait was switched from != to -lt, which is a safer comparison and avoids possibility of an infinite loop.

Fixes #2380

#3143 has another similar approach, which relies on conditionally checking for sleep or ping binaries to provide a sleep functionality.

@pdewilde pdewilde requested a review from a team as a code owner May 23, 2025 20:45
read -rt "$1" <> <(:) || :
fi
# Fallback to busy wait.
while [[ $SECONDS -lt $1 ]]; do
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


# Bash 4.0 and above supports read.
if [[ -n "$BASH_VERSINFO" && "${BASH_VERSINFO[0]}" -ge 4 ]]; then
echo foo
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
echo foo

Remove debug logs

fi
# Fallback to busy wait.
while [[ $SECONDS -lt $1 ]]; do
echo bar
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
echo bar

Same here

@pdewilde
Copy link
Author

Changes incorporated here: #4146

@pdewilde pdewilde closed this Dec 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

safe_sleep.sh inadvertently top 100% CPU

3 participants