Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 为什么断开的网络连接会导致stdin上出现EOF?_C_Multithreading_Sockets_Stdin - Fatal编程技术网

C 为什么断开的网络连接会导致stdin上出现EOF?

C 为什么断开的网络连接会导致stdin上出现EOF?,c,multithreading,sockets,stdin,C,Multithreading,Sockets,Stdin,我有一个简单的服务器,它在一个单独的线程中等待网络连接,然后定期向客户机发送信息。主线程通过stdin接受命令。我不明白的是,为什么stdin在客户端终止时收到EOF 对于下面的示例代码,客户端可以像命令行中的“nc 127.0.0.1 1234”一样简单。当客户端被“kill”或Ctl-C中断时,服务器将由于stdin上的EOF而退出。我当然希望您能对这种行为进行解释,并提供一种使服务器保持运行的解决方法 static void *WaitForConnections(void *p) {

我有一个简单的服务器,它在一个单独的线程中等待网络连接,然后定期向客户机发送信息。主线程通过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设置为eppe,代码可以处理它。

什么EOF?什么
stdin?
在Xcode中调试时,连接失败会暂停执行。如果在此之后步进主线程,那么从stdin读取的getchar()将返回EOF。谢谢!我想getchar()中的EOF只是依赖于系统的终止的一部分,但对我来说是个麻烦。