我正在运行一个服务器和一个客户端。我正在我的计算机上测试我的程序。
这是在服务器中向客户端发送数据的函数:
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;
}
当客户端退出时,它向服务器发送"BYE",服务器会用上述函数进行回复。我将客户端连接到服务器(在一台计算机上完成,有2个终端),当客户端退出时,服务器崩溃了 - 它从未打印出
15
。你有任何想法为什么吗?有没有任何想法如何测试原因?谢谢。
编辑:这是我如何关闭客户端的方式:
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);
}
顺便提一下,如果我跳过这段代码,也就是只留下close(_sockfd)
而不通知服务器一切都好的意思——服务器不会崩溃。
编辑2:这是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 +++
破管道会导致我的程序崩溃吗?为什么不只是通过send()返回-1呢?
msg.c_str()
复制到一个char
数组中,然后再传递该数组。 - phoxis