我正在运行服务器和客户端。我正在我的计算机上测试我的程序。
这是服务器中向客户端发送数据的函数:
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 呢?