6/15/2007

TIP: Dos Sleep

I needed a batch file to sleep between starting up a couple of processes but dos doesn't support sleep. Google found me this result which gave me the idea but their solution is wrong.

The actual answer is this:

ping 1.1.1.1 -n 1 -w 10000 > nul
In this case we are pinging a non-existent IP address, once, and timing out in 10000 milliseconds.

Of coarse you could pop this into a sleep.bat to centralize it
cd c:\windows\system32
copy con sleep.bat
@echo off
ping 1.1.1.1 -n 1 -w %1% > nul
ctrl-Z
Now you can just type "sleep 5000" to sleep for 5 seconds.

The actual resolution of this timer is one second or more. Any number less than one second is going to end up with a 1 second'ish delay.

The cost of this is one network ping with a standard 32 byte payload. The total message is 74 bytes on a Windows XP machine. This is low cost for a couple of sleeps in your program. If you want to do this all the time then you may want a less hackey solution.

The better solution might be to use the Windows Resource Kit which includes a sleep.exe command.

3 comments:

Unknown said...

Thanks. Is there any guarantee that 1.1.1.1 is not a valid email address? I did try 0.0.0.0 and it said "Destination specified is invalid.".

Interestingly, "ping 257.1.1.1 -n 1 -w 10000" also worked. Perhaps that could be a valid address too.

Edward Sumerfield said...

The owner of the IP is "Internet Assigned Numbers Authority" (http://www.networksolutions.com/whois/results.jsp?ip=1.1.1.1) and presumably there is no machine hanging off it. I don't know anything about the likelihood of that changing. If you are concerned about it you should find that "less hacky" solution.

As for 257, since the C level libraries that work with IP addresses store each number in a byte you are naturally limited to numbers between 0 and 255 (http://msdn2.microsoft.com/en-us/library/zx63b042(VS.80).aspx).

So, it is likely that pinging 257 is wrapping the byte, but that would be platform specific. On my Mac, I tried pinging ping google's IP with a 319... instead of a 64... but it didn't work so something else must be going on.

Anonymous said...

This is a very clever idea, thanks