gpt4 book ai didi

c - 为什么断开的网络连接会在stdin上导致EOF?

转载 作者:行者123 更新时间:2023-12-03 11:52:03 25 4
gpt4 key购买 nike

我有一个简单的服务器,它在单独的线程中等待网络连接,然后定期将信息发送到客户端。主线程通过stdin接受命令。我不明白的是为什么客户端终止时stdin会收到EOF。

对于以下示例代码,客户端可以像命令行中的“nc 127.0.0.1 1234”一样简单。当客户端被“kill”或Ctl-C中断时,服务器将由于stdin上的EOF而退出。对于此行为的说明和使服务器保持运行的变通办法,我当然将不胜感激。

static void *WaitForConnections(void *p) {
int sockfd, newsockfd;
struct sockaddr_in server = { sizeof(server), AF_INET, htons(1234), INADDR_ANY};

if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket call failed");
exit(1);
}

if ( bind(sockfd, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) == -1){
perror("bind call failed");
exit(1);
}

if ( listen(sockfd, 0) == -1 ) {
perror("listen call failed");
exit(1);
}

for (;;) {
if ( (newsockfd = accept(sockfd, NULL, NULL)) != -1) { // new connection
for ( ;;) {
char c = 'd';
if (send(newsockfd, &c, sizeof(c), 0) != sizeof(c)) {
break;
}
sleep(1);
}
close(newsockfd);
}
else {
break;
}
}

close(sockfd);
return NULL;
}

int main(int argc, const char * argv[]) {
pthread_attr_t attr;
pthread_t p;
void * status;

pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

if (0 != pthread_create( &p, &attr, WaitForConnections, NULL )) {
fprintf(stderr, "thread creation failed\n");
exit(1);
}

while (getchar() != EOF) {}

pthread_join(p, &status);

return 0;
}

没关系,但这是在MacOS X 10.10.1,Xcode 6.1.1和Apple LLVM 6.0下。

最佳答案

您的服务器不会因为在stdin上的EOF而退出,而是因为它尝试在断开的TCP连接上发送数据而退出,这会导致SIGPIPE信号被传递-SIGPIPE的默认操作是终止进程。

您应该使用忽略SIGPIPE

 signal(SIGPIPE,SIG_IGN);

这将导致send()/write()调用改为返回-1并将errno设置为您的代码可以处理的EPIPE。

关于c - 为什么断开的网络连接会在stdin上导致EOF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27829384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com