Skip to content

Instantly share code, notes, and snippets.

@pbosetti
Created June 4, 2014 13:39
Show Gist options
  • Save pbosetti/2c81425fc53b02b4b6ce to your computer and use it in GitHub Desktop.
Save pbosetti/2c81425fc53b02b4b6ce to your computer and use it in GitHub Desktop.
Simple timeout implementation using SIGALRM
//
// main.c
// timeout
//
// Created by Paolo Bosetti on 04/06/14.
// Copyright (c) 2014 UniTN. All rights reserved.
//
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void signal_handler(int sig);
void start_timer(useconds_t useconds);
int timeout_flag = 0;
int main(int argc, const char * argv[]) {
printf("Start...\n");
start_timer(1e6);
int i;
for (i=0; i<1e6; i++) {
if (timeout_flag == 1)
break;
usleep(10);
}
printf("end working (i=%d)\n", i);
}
void start_timer(useconds_t useconds)
{
struct sigaction sigact;
sigact.sa_handler = signal_handler;
sigact.sa_flags = SA_RESETHAND;
sigemptyset(&sigact.sa_mask);
sigaction(SIGALRM, &sigact, NULL);
ualarm(useconds, 0);
}
void signal_handler(int sig)
{
if (sig == SIGALRM) {
timeout_flag = 1;
printf("Timeout!\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment