【发布时间】:2016-06-03 11:57:47
【问题描述】:
我有一些看起来像这样的代码,我不确定如何处理永远不会执行的部分,因为该代码的一部分在等待连接时无限循环运行,当我终止程序时,它会从只有那里。
main(){
// do some stuff....
while(1) {
int newFD =
accept(sockFD, (struct sockaddr *)&client_addr, &client_addr_size);
if(newFD == -1) {
std::cerr << "Error while Accepting on socket" << std::endl;
continue;
}
if(!fork()) {
close(sockFD); // close child's sockfd - not needed here
// lalala do stuff send message here
close(newFD); // finally close its newFD - message sent, no use
return 0;
}
close(newFD); // close parent's newFD - no use here
}
// now execution never reaches here
close(sockFD); // so how to handle this?
freeaddrinfo(res); // and this?
return 0;
}
【问题讨论】:
-
我让它保持原样,我猜操作系统应该处理它?
-
对于这种情况,我想挂钩终止信号并使用它干净地退出程序。不过,一般来说,对于从未执行过的代码,请将其删除。让您的版本控制跟踪旧的死代码。
-
您的问题是关于如何处理关闭套接字,或者如何处理代码本身?
-
也许这有点简单,但你能检查一个非常高的数字然后关闭吗?
-
关闭
newFD后为什么不把return 0改成continue?
标签: c++ linux loops networking infinite-loop