Bob Bob - 6 months ago 46
C Question

Ensure program only runs for N seconds

I need to specify that a program ends after N seconds. I assume that would mean enclosing the entire program in some sort of do while loop, but I can't figure out the specifics. How would this be done?

For a very simple example, lets say I want it to run the line

printf("Hello world\n");

For N seconds


This stupid code prints hello world during at least 3 seconds

#include <stdio.h>
#include <time.h>

int main()

    time_t start_timer = time(NULL);
        printf("Hello world\n");
        if (time(NULL)-start_timer > 3)
    return 0;

Of course, if instead of just printing a message, the program performed a big computation / input/output operation / network operation, it could take longer than 3 seconds.

In that case, as a pertinent comment suggested, it would be better (but more complex, so it has to be necessary) to create a "watching" thread and check time lapse in parallel of the computation (using a cpu-passive time wait mechanism to avoid eating 100% CPU), killing the computing thread if taking too long.

(note that if a big I/O operation is in progress, the thread kill could take a while because the thread is not active at this time)