Send () my program crash

I start the server and client. I am testing my program on my computer.

This is a function on the server that sends data to the client:

int sendToClient(int fd, string msg) {

    cout << "sending to client " << fd << " " << msg <<endl;
    int len = msg.size()+1;
    cout << "10\n";
    /* send msg size */
    if (send(fd,&len,sizeof(int),0)==-1) {
        cout << "error sendToClient\n";
        return -1;
    }
    cout << "11\n";
    /* send msg */
    int nbytes = send(fd,msg.c_str(),len,0); //CRASHES HERE
    cout << "15\n";
    return nbytes;
}

when the client leaves it, it goes to the "BYE" server, and the server responds to it using the specified function. I connect the client to the server (it is done on one computer, 2 terminals), and when the client leaves the server, it never prints 15. any idea why? any idea how to check why?

thank.

EDIT: this is how I close the client:

void closeClient(int notifyServer = 0) {

/** notify server before closing */
if (notifyServer) {
    int len = SERVER_PROTOCOL[bye].size()+1;
    char* buf = new char[len];
    strcpy(buf,SERVER_PROTOCOL[bye].c_str());   //c_str - NEED TO FREE????
    sendToServer(buf,len);
    delete[] buf;
}
close(_sockfd);
}

btw, if I skip this code, that is, just leave the close(_sockfd)server without notification, everything is in order - the server is not crashing.

EDIT 2: this is the end of strace.out:

5211  recv(5, "BYE\0", 4, 0)            = 4
5211  write(1, "received from client 5 \n", 24) = 24
5211  write(1, "command: BYE msg: \n", 19) = 19
5211  write(1, "BYEBYE\n", 7)           = 7
5211  write(1, "response = ALALA!!!\n", 20) = 20
5211  write(1, "sending to client 5 ALALA!!!\n", 29) = 29
5211  write(1, "10\n", 3)               = 3
5211  send(5, "\t\0\0\0", 4, 0)         = 4
5211  write(1, "11\n", 3)               = 3
5211  send(5, "ALALA!!!\0", 9, 0)       = -1 EPIPE (Broken pipe)
5211  --- SIGPIPE (Broken pipe) @ 0 (0) ---
5211  +++ killed by SIGPIPE +++

A broken pipe can kill my program? why not just return -1 on send () ??

+2
6

, , , . , .

, . case, send SIGPIPE ; , EPEPE.

+3

MSG_NOSIGNAL:

int nbytes = send(fd,msg.c_str(), msg.size(), MSG_NOSIGNAL);
+8

SIGPIPE - "" Unix, SIGPIPE , . , , / .

(.. send() ), (, top of main()):

#include <signal.h>

int main(int argc, char ** argv)
{
   [...]
   signal(SIGPIPE, SIG_IGN); 
+3

, int len = msg.size()+1;.

int nbytes = send(fd,msg.c_str(),len,0); //CRASHES HERE

, int len = msg.size();?

+1

send , , , .

, , .

0

Linux, strace. .

strace -f -o strace.out ./server

Then take a look at the end of the log file. Perhaps this is obvious what the program did, and when it crashed, maybe not. In the latter case: put the last lines here.

0
source

All Articles