This is not a homework problem, I promise.
I'm writing a time series database implementation as a way to learn C.
I have a client/server pair that I've written. The server is currently an echo server listening to a socket on a port. The client connects to that port and sends lines of input to it. It uses readline
to get input, send
s it to the client socket, recv
s a line from the client socket, and prints the line to the terminal. Rinse, repeat. The client returns when it gets an EOF
from recv
, at which point it knows the connection is closed.
The problem is that readline
is blocking, such that if the server process is killed, i.e. I SIGINT
it, the client is still blocking on readline
. It isn't until after it send
s, then recv
s an EOF
, that it will know the server is gone.
What I want to happen is for the client to get signaled if there's an EOF
on recv
and immediately exit.
What I think I need to do is to create 3 pthreads
- 2 for a network client (send
and recv
) and 1 for the terminal. The terminal calls readline
and blocks. It accepts input, and then uses a pthread_cond_t
to signal the waiting network client send
thread to send. The network client recv
thread is constantly recv
ing, which will block. If it is an EOF
, it raises SIGINT
, the handler to which pthread_kill
s all 3 threads, fprintf
s something like "Connection closed by server.", and calls exit
(yes, I know exit
will terminate all threads anyways - it's an exercise in cleanliness and to see if I understand C).
Is this the appropriate approach? Obviously network client terminals do this all the time. What's the right approach?