Feb
7
Comments Off

Implement Timeout for one function in C

Author saurabh    Category c, sample programme, Tips     Tags

Here i have one function which is listen mode. this function listing something which i got form some device.

Here when my function is in listen mode that time i want to create timeout. if i will not get any response from particular device than i want o exit from this function and have to notify.

if during this timeout period if i will get some date from something or some action would be performed than i have to continue with work and stop this timeout.

So here i am using alarm and signal.h file for that.

First of all here i used start_timer function which take timeout as a parameters in seconds here i taken 25 seconds default. and second argument is void function pointer which function we want to call after timeout occurs. here we set alarm of 25 seconds when 25 seconds complete than its automatically sends one signal to system like interrupt. here singnal_handler function calls and this function call the timer_timeout function and we will do here other stuff after timeout. If timeout doesnt occur so we can stop this alaram by using alarm(0).  which i did here in below example.

 

Code is Given Below its not fully working you have to add your Stuff in below code.

 

#include
#include
#include 
 
struct sigaction sigact;
 
void signal_handler(int);
void (*timeout_callback)();
void start_timer(int time, void(*timout)());
void timer_timeout();
int flag = 0;
 
void main() {
 
// Your stuff
 
start_timer(25, &timer_timeout);
 
// Your Action for which u wait.
//than make change the flag value.
//and timer also.
if (flag == 0) {
stop_timer();
 
}
//continue with ur work.
 
}
void timer_timeout()
{
printf("time out occured\n");
//more stuff
}
 
void start_timer(int time, void(*timeout)())
{
timeout_callback = timeout;
sigact.sa_handler = signal_handler;
sigemptyset(&sigact.sa_mask);
sigact.sa_flags = 0;
sigaction(SIGALRM, &sigact, (struct sigaction *) NULL);
alarm(time);
 
}
 
void stop_timer()
{
printf("\nstop timer\n");
alarm(0);
flag = 1;
}
 
void signal_handler(int sig)
{
printf("siganal emittd\n");
if (sig == SIGALRM)
timeout_callback();
}
 

saurabh

hey friends i have completed my B.Tech in CE from Ganpat University & now i am working as Android Middleware & Application Developer in one Private firm. i really enjoy programming…!!

More PostsFacebook

You may like to read this also....

Comments are closed.

Follow us on Twitter! Follow us on Twitter!

Search in this website

our sponsors

latest comments

Find us on Facebook

Top Authors

35 posts
saurabh
22 posts
10 posts

Find us on stackoverflow

Polls

Tell us who you are

View Results

Loading ... Loading ...

My Bookmarks

Sponsers Link