gpt4 book ai didi

c - 从套接字读取时如何处理阻塞的 read() 调用?

转载 作者:太空宇宙 更新时间:2023-11-03 23:39:45 25 4
gpt4 key购买 nike

出于自学目的,我正在用 C 语言编写一个简单的 IRC 客户端程序,但我无法理解 read() 的行为。调用从套接字文件描述符读取时的函数。

下面的代码片段工作并打印与运行相同的输出

$ echo "NICK gertrudes\r\nUSER a 0 * d\r\n" | nc chat.freenode.net 6667

在终端中,这与我的程序到目前为止打印的相同:

while ((n = read(sockfd, buffer, sizeof(buffer)-1)) > 0) {
printf("\nloop\n");
buffer[n] = '\0';
if (fputs(buffer, stdout) == EOF)
error("fputs");
}
if (n < 0)
error("reading from socket");

printf("out of the loop\n");

我不明白的是为什么程序永远不会到达最后的 printf打电话,而是坐在那里,好像在等待来自服务器的更多信息。这是否意味着最后的回复比 0 长并且 IRC 服务器在我发送另一个命令之前不会发送任何新内容?

如果是这样(冒着跑题的风险),和read()正在阻塞,当程序等待调用返回时,我应该在哪里编写向服务器发送命令的逻辑?

最佳答案

What I fail to understand is why the program never gets to the final printf call, and rather sits there as if waiting for more from the server.

Item>正在等待来自服务器的更多。 read() 将在对等方断开连接时返回零,之前不会。

关于c - 从套接字读取时如何处理阻塞的 read() 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49090790/

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