Search code examples
csignalssleepselect-function

Using sleep and select with signals


I want to use the select() function to wait for 1 second, as my program uses signals to control stuff, so sleep() would return prematurely. The weird thing is that when using select() it also returns prematurely.

I am calling select like this

struct timeval timeout;    
timeout.tv_sec = 10;  
timeout.tv_usec = 1000000; 
select (0 ,NULL, NULL, NULL, &timeout);

but whenever a signal arrives, it returns (I am using a nano second timer for the signal)

Anyone knows why?


Solution

  • Try something like this:

    struct timespec timeout;
    timeout.tv_sec = 10;
    timeout.tv_nsec = 0;
    while (nanosleep(&timeout, &timeout) && errno == EINTR);
    

    The "remaining time" pointer to nanosleep will take care of letting you restart the sleep with the necessary amount of remaining time if it gets interrupted.