APLawrence.com -  Resources for Unix and Linux Systems, Bloggers and the self-employed

2003/11/13 Unix/Linux sleep

There are two aspects to sleep: a voluntary sleep, where a process needs to delay for whatever purpose and deliberately calls "sleep" with some time argument, and involuntary, where the kernel scheduling code puts the process to sleep either because some resource it wants is slow, or unavailable, or because it's just time for some other process to use the CPU. There are two aspects to sleep: a voluntary sleep, where a process needs to delay for whatever purpose and deliberately calls "sleep" with some time argument, and involuntary, where the kernel scheduling code puts the process to sleep either because some resource it wants is slow, or unavailable, or because it's just time for some other process to use the CPU.

We'll talk about voluntary sleeps here. First, there is always a limit to how long you can sleep. That's probably going to be limited by the size of an unsigned integer, and therefore your longest possible sleep will be that many seconds. That's a long, long time though - more than any program would ever need.

The shortest possible sleep is 1 second, so programs that need shorter resolution have to use something other than "sleep". Some systems have calls like "nap" for this.

At the shell, "sleep 10" goes awy for 10 seconds. This is useful for loops:

while true
do
ls -l
echo "sleeping"
sleep 10
done
 

Sleeps can of course be interrupted by signals, which causes it to end earlier than expected, and of course a busy system can cause the sleep to run longer than your intention. Just because you say "sleep 10" does not mean your next statement will be exactly 10 seconds later. C programs use "sleep(10)" in the same way.

Sleep can be internally implemented using "alarm()", and if it is, there are gray areas: what happens if you set an alarm to go off in ten seconds (the alarm will generate a signal 10 seconds from now) and do a 5 second sleep a second or so later? Is the alarm still set? Maybe, but it's system dependent.

See also Higher resolution timers in the shell.



Got something to add? Send me email.





(OLDER)    <- More Stuff -> (NEWER)    (NEWEST)   

Printer Friendly Version

-> -> Unix/Linux process sleep




Increase ad revenue 50-250% with Ezoic


More Articles by

Find me on Google+

© Tony Lawrence



Kerio Samepage


Have you tried Searching this site?

Unix/Linux/Mac OS X support by phone, email or on-site: Support Rates

This is a Unix/Linux resource website. It contains technical articles about Unix, Linux and general computing related subjects, opinion, news, help files, how-to's, tutorials and more.

Contact us





That's the thing about people who think they hate computers. What they really hate is lousy programmers. (Larry Niven)

Technology is anything that wasn’t around when you were born. (Alan Kay)







This post tagged: