设置TCP connect超时时间的2种方法

1.常用方法

设置socket非阻塞,之后使用select等设置超时时间

2.使用alarm信号量

需要注意:线程信号量掩码是线程私有的,当指定进程递交信号量时,操作系统会将信号量递交至该进程中未屏蔽该信号量的所有线程中的随机之一。

见 man 7 signal:

  A  signal  may be generated (and thus pending) for a process as a whole

       (e.g., when sent using kill(2)) or for a specific thread (e.g., certain

       signals, such as SIGSEGV and SIGFPE, generated as a consequence of exe-

       cuting a specific machine-language instruction are thread directed,  as

       are  signals  targeted  at a specific thread using pthread_kill(3)).  A

       process-directed signal may be delivered to any one of the threads that

       does  not  currently  have the signal blocked.  If more than one of the

       threads has the signal unblocked, then the kernel chooses an  arbitrary

       thread to which to deliver the signal.



皆抄袭自《TCP高效编程》

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 CSDN 开发的 C 知道 中,您可以使用一些套接字选项来设置 TCP 连接的超时时间。一常用的方法是使用 `connect()` 函数之前,使用 `setsockopt()` 函数设置 `SO_RCVTIMEO` 或 `SO_SNDTIMEO` 选项。 以下是一个示例代码片段,展示了如何设置连接超时时间为 5 秒: ```c #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> int main() { int sockfd; struct sockaddr_in server_addr; int connect_timeout = 5; // 超时时间为 5 秒 // 创建套接字 sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { perror("socket"); exit(1); } // 设置连接超时选项 struct timeval timeout; timeout.tv_sec = connect_timeout; timeout.tv_usec = 0; if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == -1) { perror("setsockopt"); exit(1); } if (setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) == -1) { perror("setsockopt"); exit(1); } // 设置服务器地址 server_addr.sin_family = AF_INET; server_addr.sin_port = htons(8080); // 设置服务器端口号 server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 设置服务器 IP 地址 // 连接服务器 if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) { perror("connect"); exit(1); } // 连接成功,进行后续操作 // 关闭套接字 close(sockfd); return 0; } ``` 在上述示例中,我们使用了 `setsockopt()` 函数来设置 `SO_RCVTIMEO` 和 `SO_SNDTIMEO` 选项,将超时时间设置为 5 秒。这样,在调用 `connect()` 函数时,如果连接超时或者连接过程中发生错误,会返回相应的错误码。 请注意,以上代码仅用于演示如何设置连接超时时间,实际应用中可能需要根据具体情况进行适当修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值