I have a server which allows a dedicated client to connect
and pass data back and forth. The server which I coded runs on Linux and the client an executable I didn't code, runs on windows. My problem is that when the server is stopped and restarted while the client is connected I sometimes have to wait about a minute before I can get them talking again by stopping both of them. I suspect that the socket is still alive and thinks a connection is still there until it times out or something. I close the server which is running as a thread by exiting a while loop when a ctrl-c key combination is pressed.
while(!quit), where quit is set to true when a ctrl-c
After I break the while loop condition, I've tried the following with no luck.
pthread_exit(0); the while no longer stops with this
exit(0); results in a segfault
close(socketFileDescriptor); has no effect
If I keep the server running and stop and start the client
it will reconnect but will no longer exchange data.
At this point I'm not sure if it's my code or the software I'm working with.
I have not set any socket options or have any code that removes sockets. I read that exit(0) should close all open file descriptors. The only thing I've used is
fcntl() to set the non_blocking option.
So I guess what my question comes down to is what is the proper way to gracefully shutdown a server running as a thread. Or have I tried the right things and the problem is not with my code?
Here is how I create the socket:
struct sockaddr_in server;
struct sockaddr_in client;
unsigned int serverDataLength, clientDataLength;
int serverSock_fd, client_fd;
serverSock_fd = socket(AF_INET, SOCK_STREAM, 0);
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(5000);
serverDataLength = sizeof(server);
bind(serverSock_fd,(struct sockaddr * )&server
clientDataLength = sizeof(client);
client_fd = accept(serverSock_fd,(struct sockaddr * )&client,&clientDataLength);
int flag = fcntl(client_fd,F_GETFL,0);