Re: Implementing a Timeout in C/C++



wade.lindsey@xxxxxxxxx writes:

Anyway, what I'm trying to do is:

while (ERROR_CONDITION)
{
<Wait for either 10 Seconds to expire or ERROR_CONDITION == 0>
}

basically, a straitforward timeout...

Is there anyway to achieve this without using sleep? I have other
actions going on in the background that I don't want to suspend, I just

What sort of error condition do you have going? For certain types of
situations select() (C's :-)) can be most beneficial, as it will yield
processor time to others for use.

You could certainly check the value of time() [for real seconds] or
clock() [for process seconds]; or gettimeofday() [if you want finer
precision].

Your best bet may be to use alarm() with a handler. For instance:

#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

volatile sig_atomic_t got_alarm = 0;

void handle_alarm(int signum)
{
got_alarm = 1;
}

int main(void)
{
int errcond = 1;
void (*sigrslt)(int);

sigrslt = signal(SIGALRM, handle_alarm);
if (sigrslt == SIG_ERR)
return EXIT_FAILURE;

alarm(5);
while (errcond && !got_alarm)
;
return EXIT_SUCCESS;
}
.