Timeouts in C

Timeouts are important for programs that connect to external resources or that otherwise need to bound execution time. Implementing timeouts in C requires careful use of signal handling and alarm functions.

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

void timeout_handler(int signum) {
    printf("timeout\n");
    exit(0);
}

void execute_with_timeout(void (*func)(), int timeout_seconds) {
    signal(SIGALRM, timeout_handler);
    alarm(timeout_seconds);
    func();
    alarm(0);  // Cancel the alarm if the function completes before timeout
}

void task1() {
    sleep(2);  // Simulating a task that takes 2 seconds
    printf("result 1\n");
}

void task2() {
    sleep(2);  // Simulating a task that takes 2 seconds
    printf("result 2\n");
}

int main() {
    printf("Starting task 1 with 1 second timeout:\n");
    execute_with_timeout(task1, 1);

    printf("\nStarting task 2 with 3 seconds timeout:\n");
    execute_with_timeout(task2, 3);

    return 0;
}

In this C implementation:

  1. We define a timeout_handler function that will be called when a timeout occurs.

  2. The execute_with_timeout function sets up a signal handler for SIGALRM and uses the alarm function to schedule a timeout.

  3. We define two tasks, task1 and task2, each simulating a 2-second operation.

  4. In the main function, we execute task1 with a 1-second timeout and task2 with a 3-second timeout.

Running this program shows the first operation timing out and the second succeeding:

$ gcc timeouts.c -o timeouts
$ ./timeouts
Starting task 1 with 1 second timeout:
timeout

Starting task 2 with 3 seconds timeout:
result 2

Note that this implementation uses UNIX-specific signal handling, which may not be available on all systems. For a more portable solution, you might need to use platform-specific APIs or third-party libraries that provide timeout functionality.