views:

198

answers:

2

I have a client-server system, where the client needs to fork a child, and return its pid back to the server. After this, it has to keep the connection to the server alive, through which it keeps sending the server log information about the child and other requests that it might want to send as part of debugging information.

My question is, how can this be done? Do I every time make a connection to the server, send it the pid and ask it to log the request [as I can have multiple clients sending requests to the server at the same time] or is there some other way also to do this?

+1  A: 

If there are no stateful firewalls/NAT with timeout between the client and server, a TCP connection will last indefinitely, without any data needing to be sent. You can set some socket options that will periodically send packets not containing any data (and break the connection if no response is received) - search for SO_KEEPALIVE.

If you're talking about some specific HTTP server, it probably has an option for how long to allow a connection to last without any requests, e.g. KeepAliveTimeout in apache.

wrang-wrang
+1  A: 

You need to be clearer about the process structure than you are at the moment. Does the server process stay alive independently of the client processes? Is it listening on a well known port number? When does the first (parent) process on the client side connect to the server?

You say the client forks a child and then lets the server know about the child PID. Does the child also communicate with the server? Does it open an independent connection to the server, or does it preempt the parent process's connection, or do the child and parent attempt to share a single connection to the server? How do you coordinate the access on the single connection?

One common setup for such a system is:

  • The server process is started up as a daemon that listens on a well-known or configured port.
  • The initial client (parent) process establishes a connection to the server.
  • The secondary client (child) process disconnects the inherited connection and establishes its own connection to the server.

There are two modes of operation for the connections:

  1. The client processes open the connection, write a message, maybe wait for a response, and close the connection each time. This is the mechanism used by web browsers because the web provides stateless connections.
  2. The client processes open a connection and keep it open (and the server doesn't close the connection until there is an emergency or the client agrees (or requests) to close it. This mechanism is typically used by database clients connecting to a database server.

Both modes work - they have different implications for overhead (it takes long if you connect each time) and resource usage (persistent connections use up more resource in the server; the clients are not seriously affected).

Jonathan Leffler