Server-maintained timeouts

In this scenario, a server is providing some kind of service to a client, and the client has the ability to specify a timeout. There are lots of places where this is used. For example, you may wish to tell a server, "Get me 15 seconds' worth of data," or "Let me know when 10 seconds are up," or "Wait for data to show up, but if it doesn't show up within 2 minutes, time out."

These are all examples of server-maintained timeouts. The client sends a message to the server, and blocks. The server receives periodic messages from a timer (perhaps once per second, perhaps more or less often), and counts how many of those messages it's received. When the number of timeout messages exceeds the timeout specified by the client, the server replies to the client with some kind of timeout indication or perhaps with the data accumulated so far — it really depends on how the client/server relationship is structured.

Here's a complete example of a server that accepts one of two messages from clients and a timeout message from a pulse. The first client message type says, "Let me know if there's any data available, but don't block me for more than 5 seconds." The second client message type says, "Here's some data." The server should allow multiple clients to be blocked on it, waiting for data, and must therefore associate a timeout with the clients. This is where the pulse message comes in; it says, "One second has elapsed."

In order to keep the code sample from being one overwhelming mass, I've included some text before each of the major sections. You can find the complete version of time1.c in the Sample Programs appendix.