theStig
theStig

Reputation: 610

How to time events

What is the best practice behind handling timed events in C? The scenario I'm looking at is that i need to resend data to the server from the client if i do not receive a response from the server within a second.

Code would be nice, but explanation of the concept would be far more valuable.

Upvotes: 0

Views: 79

Answers (3)

Jeremy Friesner
Jeremy Friesner

Reputation: 73294

If your program is using non-blocking I/O and doing its blocking inside of select() or poll(), these functions have an optional timeout argument that lets you specify that the select()/poll() call should return after a certain amount of time has elapsed, even if no I/O events have occurred. You can use that functionality to get your program to perform an action at intervals.

Upvotes: 0

Mats Petersson
Mats Petersson

Reputation: 129524

Most operating systems have some form of timer. In Linux/Unix/Posix you have alarm, and in windows there's SetTimer

So, basiclaly, you send a message off, and set a timer to a time when you expect to have got a reply - 1s, 10s, 30s - whatever makes senses for your circumstances.

If you get a reply, you cancel the timer, and do whatever else you plan to do with the reply. If no reply arrives before the timer fires, you send again [it may mean "signal some semaphore or flag" to send again, rather than actually doing that in the handler for the timer].

For other operating systems, you'll have to tell us what you are looking at, but most have some sort of mechanism to handle "tell me when X time has passed".

Upvotes: 2

Mihai8
Mihai8

Reputation: 3147

This requires a prior synchronization between client and server. Also, you must have a library for event management. Such of libraries are mentioned in timer and I/O Event Manager library.

Upvotes: 0

Related Questions