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.
In this C implementation:
We define a
timeout_handler
function that will be called when a timeout occurs.The
execute_with_timeout
function sets up a signal handler for SIGALRM and uses thealarm
function to schedule a timeout.We define two tasks,
task1
andtask2
, each simulating a 2-second operation.In the
main
function, we executetask1
with a 1-second timeout andtask2
with a 3-second timeout.
Running this program shows the first operation timing out and the second succeeding:
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.