I'm working on sockets in linux using telnet. Every things seems to work perfectly fine but when i kill the telnet, it will terminate my socket connection which i don't want.
Here is the code:
try {
while (_this->running) {
// MAIN CYCLE OF THE SOCKET
// sends a messages from the queue through the socket
while (_this->messages.size()>0) {
//cout << "Queue size: " << _this->messages.size() << endl;
string currentMessage = _this->messages.front();
currentMessage.append("\n");
cout << "write: " << _this->newSockFd << endl;
int n = write(_this->newSockFd, currentMessage.c_str(), currentMessage.length());
cout << "n: " << n << endl;
if (n < 0) {
cout << "Throws an exception " << endl;
throw string("ERROR writing to socket");
}
_this->messages.pop();
//cout << "Message [" << currentMessage << "] written into the socket." << endl;
}
// wait for a new message
pthread_cond_wait(&_this->numberOfMessagesCondition, &_this->mutexSendMessage);
// END OF THE MAIN CYCLE OF THE SOCKET
}
} catch (string exception) {
cout << "Client Disconnected: " << exception << endl;
_this->newSockFd = -1;
}
i tried to test it. It seems the error is in the write function is used to write my data through the socket.When we kill the telnet and write is executed. It just terminate without returning any value.Which is not suppose to happen though.
Any help in this regard will be highly appreciated.
How can I know if an endpoint is still valid or not?
I expected the write method raise a sort of exception or return an error, so I can handle this and do something in the server side.
But the problem is that when the program execute the instruction write, it just dies, without return any kind of error.
Is it that write() is generating a SIGPIPE due to a broken socket?
Edit:
You may be able to setsockopt() with SO_NOSIGPIPE, but I don't think this is portable and may not be available. Maybe set the SIGPIPE handler to SIG_IGN.