小编Pau*_*sta的帖子

SO_KEEPALIVE 在调用 write() 期间不起作用?

我正在开发一个套接字应用程序,它必须对网络故障具有健壮性。

该应用程序有 2 个正在运行的线程,一个等待来自套接字的消息(一个 read() 循环),另一个向套接字发送消息(一个 write() 循环)。

我目前正在尝试使用 SO_KEEPALIVE 来处理网络故障。如果我只在 read() 上被阻止,它就可以工作。连接丢失(移除网络电缆)几秒钟后,read() 将失败并显示“连接超时”消息。

但是,如果我在网络断开连接后(并且在超时结束之前)尝试写入(),则 write() 和 read() 都将永远阻塞,不会出错。

这是一个剥离的示例代码,它将 stdin/stdout 定向到套接字。它侦听端口 5656:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>

int socket_fd;

void error(const char *msg) {
    perror(msg);
    exit(1);
}

//Read from stdin and write to socket
void* write_daemon (void* _arg) {
    while (1) {
        char c;
        int ret = scanf("%c", &c);
        if (ret <= 0) error("read from stdin"); …
Run Code Online (Sandbox Code Playgroud)

c sockets keep-alive

5
推荐指数
1
解决办法
8934
查看次数

标签 统计

c ×1

keep-alive ×1

sockets ×1