正确关闭套接字 - 读取时另一侧卡住 [英] Proper closure of a socket - other side gets stuck when reading

查看:73
本文介绍了正确关闭套接字 - 读取时另一侧卡住的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

while (((connfd = accept(listenfd)) != -1){
    if (fork() == 0) {
        write(connfd, buffer ,strlen(buffer));
        close(connfd);
    }
}

大家好,我收到了一个 OS 考试的样题.假设我有一个使用上述代码处理多个客户端的 TCP 服务器.正如问题中所指定的,其余的代码应该是有效的.现在,每次客户端连接到该服务器时,它都会从中读取数据,然后卡住.这个问题的正确答案是它发生是因为服务器没有正确关闭与客户端的连接.

Hi all, I got a sample question for an exam at OS. Let's say I have a TCP server which handles multiple clients, using the above code. As specified in the question, the rest of the code should be valid. Now, each time a client connects to this server, it reads data from it and then gets stuck. The correct answer to the question is that it happens because the server doesn't close the connection with the client properly.

我不确定我是否完全理解,不是

I'm not sure if I get it completely, isn't

关闭(套接字)

够了吗?就我而言,当一个套接字被一侧关闭时,另一侧读取 EOF 并返回 0.考虑到客户端在读取时卡住了,它不应该到达那个 EOF 并继续前进?

enough? As far as I'm concerned, when a socket is closed by one side, the other side reads EOF and returns 0. Considering the client gets stuck while reading, it shouldn't get to that EOF and move on?

推荐答案

fork() 将在子进程中返回 0,在父进程中返回正 pid.因此 close(connfd); 只会在子进程中被调用.

fork() will return 0 in the child process and a positive pid in the parent process. Therefore the close(connfd); will be invoked only in the child process.

然而,父进程做了accept并且它仍然持有一个打开的文件描述符到套接字.它也需要关闭它.直到所有打开的文件描述符都关闭时,套接字才会关闭.也就是说,你需要像

However, the parent process did the accept and it still holds an open file descriptor to the socket. It too needs to close it. The socket will not be shut down until all opened file descriptors are closed. That is to say, you need something like

pid_t child_pid = fork();
if (child_pid == 0) {
    write(connfd, buffer ,strlen(buffer));
    close(connfd);
}
else if (child_pid > 0) {
    // parent
    close(connfd);
}
else {
    // a fork error occurred, handle and remember to close(connfd)
}

这篇关于正确关闭套接字 - 读取时另一侧卡住的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆