[prog] making statements wait x number of seconds

Almut Behrens almut-behrens at gmx.net
Thu Sep 2 16:56:53 EST 2004


On Wed, Sep 01, 2004 at 09:30:25PM -0400, aec wrote:
> 
> Several times however, I have needed to make the program 
> wait x number of seconds before proceeding.
> 

In addition to the various sleep-calls already mentioned, there is also
another popular method to wait on a sub-second level, namely to use the
'select' system call.  (I know you originally only asked for ways to
"wait x number of seconds", but it never does any harm to know of other
more versatile techniques...)

select is primarily meant for waiting on filehandles (mainly used with
sockets, pipes and stuff like that).  As those occasionally will not
get ready in time, select has a builtin timeout facility with usec
resolution, which you can, of course, divert from its intended use, by
specifying no filehandles at all.

This has the advantage of being somewhat more portable than other newer
methods. select has been around in Unix for a very long time. It should
thus compile and run on anything unix-ish (not on Windows, though!).

Portability may not be your biggest concern at the moment, but think of
it this way:  anything useful you start to write has a certain tendency
to grow and get more sophisticated with time.  And there may come the
moment when you'd like to share it with the world.  Once you've done
that, it's more than likely someone will come along who'd like to build
it for that exotic OS/platform you never thought would even exist.  And
you wouldn't want them having to wade through your code, would you? ;)

Okay, here's a snippet showing how to use it:

#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>

int main(void) {
    
    struct timeval tv;
    int n;

    for (n = 0; n <= 10; ++n) {                                                                                         

        tv.tv_sec  = 0;
        tv.tv_usec = 500000;  /* wait 0.5 sec */
    
        select(0, NULL, NULL, NULL, &tv);

        printf("\nn = %i\n", n);
    }
    return 0;
}

To make this a little less unwieldy, you'd probably want to wrap it up
in a function, so you could call it something like delaysec(1.35);
This would, BTW, also nicely solve the following side issue: on linux
(and some System V variants) select modifies the timeout struct upon
returning so you'd need to reinitialize the values every time, when
repeatedly calling select in a loop, for example. Wrapped in a function
this would happen automatically.  (Splitting up a float value like 1.35
into its sec/usec parts is left as an excercise for the reader :)

Almut



More information about the Programming mailing list