Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to Implement Timeout for one function in C

Tags:

c

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 response from device than i have to continue with work and stop this timeout and there is no limits to complete this work in any time duration.

So how can i implement this thing for a function.

Any body please can me help me to implement this thing with timeout functionality.

like image 500
user1089679 Avatar asked Jan 31 '12 04:01

user1089679


People also ask

How to implement timeout in C?

select() timeoutstruct timeval timeout;timeout. tv_sec = 1;timeout. tv_usec = 500000;select(max_socket+1, &copy, 0, 0, &timeout); In this case, select() returns after a socket in fd_set copy is ready to read or after 1.5 seconds has elapsed, whichever is sooner.

What is C timeout?

The timeout specifies the maximum time to wait. If you pass a null pointer for this argument, it means to block indefinitely until one of the file descriptors is ready. Otherwise, you should provide the time in struct timeval format; see Time Types.

Why is setTimeout executed at last?

setTimeout schedules the function for execution. That scheduler doesn't do its thing until after the current thread yields control back to the browser, e.g. after the last logging statement has executed.

How to Stop a function after some time in javascript?

The clearTimeout() method stops the execution of the function specified in setTimeout(). The window.clearTimeout() method can be written without the window prefix.


1 Answers

Depending on how you are waiting for a response from this device, the answer to your question will be different. The basic framework is:

int do_something_with_device()
{
    if (!wait_for_response_from_device()) {
        return TIMEOUT_ERROR;
    }
    // continue with processing
}

As for how you implement wait_for_response_from_device(), well, every device is different. If you're using sockets or pipes, use select(). If you're interfacing with something that requires a busy-wait loop, it might look like:

int wait_for_response_from_device()
{
    time_t start = time(NULL);
    while (time(NULL) - start < TIMEOUT) {
        if (check_device_ready()) {
            return 1;
        }
    }
    return 0;
}

Naturally, the implementation of check_device_ready() would be up to you.

like image 93
Greg Hewgill Avatar answered Sep 23 '22 02:09

Greg Hewgill