Last Updated: December 26, 2018
·
3.08K
· funkaoshi

Using poll Instead of sleep to Delay a Program

The sleep() function in C will delay your program for some number of seconds you specify. If you want to delay your program for some number of milliseconds, then clearly sleep() will not work. A good alternative to sleep() is the poll() function. Normally, this is used to check if there is data to be read from a group of file descriptors; it can also double as simple sleep command. poll() takes three parameters, an array of structures (struct *pollfd), the number of elements in the array (unsigned int), and the number of milliseconds to wait for data (int). By ignoring the first two parameters, you can use poll() as a higher resolution sleep(). Simply set the first two parameters to 0 when calling the function, and set the timeout to be however many milliseconds you wish to delay your program. I use this when writing simple simulators at work, and it works well enough.

2 Responses
Add your response

Or you could use "usleep" (takes microseconds as input)

over 1 year ago ·