Wednesday, November 7, 2007

How to sleep using select() call

On many UNIX systems, the sleep() system call does not support msec granularity. But using the select() system call, the process can sleep at micro sec granularity. Here is how it can be done to sleep in milli sec granularity:

/*
* sleepms(): sleep (msecs granularity) using select.
*/
int sleepms(int msecs)
{
struct timeval timeout;
if(msecs == 0)
{
return 0;
}
timeout.tv_sec = msecs/1000; /* in secs */
timeout.tv_usec = (msecs % 1000) * 1000; /* in micro secs */
if((select(0,NULL,NULL,NULL,&timeout))==-1)
{
perror("select failed\n");
return -1;
}
return 0;
} /* sleepms()*/

2 comments:

Anonymous said...

Hey Good way to sleep.

Anonymous said...

Excellent example. Thank you.