Reputation: 6240
I'm making a socket server which has 2 threads, each running in a loop. The first looks for new connections and the second reads data from sockets which are already connected and replies to them. The problem is in the second one. 'write' function breaks the loops somehow and causes the program to finish... No errors occur... That is the problem.
The following code is a 2nd thread's function. If I don't write anything to a socket, the program runs well
void* SocketServer::threadSocketsRead( void* thisServer )
{
SocketServer* server;
int key,
playersNumber,
requestLength;
Player* player;
char message[256];
string reply;
server = (SocketServer*)thisServer;
while ( 1 )
{
playersNumber = server->players.size();
for ( key = 0 ; key < playersNumber ; key ++ )
{
player = server->players[key];
requestLength = read ( player->socket , (void*)&message , 255 );
if ( requestLength < 0 )
{
perror ( "read" );
}
else
{
/*
If I uncomment the line, it will write data to
the socket and finish the whole program.
If I do no uncomment it, the programs runs in a loop further.
*/
//int result = write ( player->socket , "reply\0" , 6 );
};
}
sleep(1);
}
}
Upvotes: 1
Views: 155
Reputation: 182619
You're probably writing to a dead socket and getting a SIGPIPE
who's default action is to terminate the program. You can:
MSG_NOSIGNAL
to send(2)
SO_NOSIGPIPE
using setsockopt
(it's not portable)Upvotes: 3