I am developing a simple server/client chat app in c++ using unix sockets and there is one thing bothering me.
If I run the chat client in terminal (i'm using a mac) and close the client with CTRL + C the four-way handshake is done and connection closes correct.
If I instead choose to close the terminal window, in which the client is running, the client sends a bunch of packets to the server.
Close client with CTRL + C:
Close client by closing terminal window:
Would be great if someone could explain to me what is happening.
Client code:
void writeString(int FD, const char* data, size_t n){
size_t bytesLeft = n;
ssize_t bytesWritten = 0;
const char *cBuffer = (char*) data;
while ((bytesWritten = write(FD, cBuffer, bytesLeft)) > 0) {
bytesLeft -= bytesWritten;
cBuffer += bytesWritten;
}
}
bool writeInt(int FD, int intToWrite){
intToWrite = htonl(intToWrite);
write(FD, &intToWrite, sizeof(intToWrite));
}
void writeMessage(int FD, int type, int ID, string message){
if(type == 1){
int messageSize = (int) message.length();
writeInt(FD, type);
writeInt(FD, ID);
writeInt(FD, messageSize);
writeString(FD, message.c_str(), messageSize);
}
}
while (!connectionClosed) {
FD_SET(socketFD, &rset);
FD_SET(0, &rset);
int maxfd = max(0, socketFD) + 1;
select(maxfd, &rset, NULL, NULL, NULL);
if(FD_ISSET(0, &rset)){
getline(cin, input);
writeMessage(socketFD, 1, ID, input);
}else if(FD_ISSET(socketFD, &rset)){
int type = 0;
if(readInt(socketFD, type) == 0)
connectionClosed = true;
readMessage(socketFD, type, ID);
}
}
close(socketFD);
SIGHUP
to catch the terminal window going away, then close the socket and exit. – Nikolai FetissovSIGHUP
and maybeSIGSTOP
and closing socket and exiting. – Nikolai Fetissov