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);
while(1)
{
printf("Hello world\n");
if (time(NULL)-start_timer > 3)
{
break;
}
}
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)