gpt4 book ai didi

c - Linux 管道的 write() 超时

转载 作者:行者123 更新时间:2023-12-05 03:55:11 38 4
gpt4 key购买 nike

如何在 Linux 管道上为 write() 设置超时?

示例代码:

int fd_pipe = open("/run/some/pipe", O_RDWR);

// here i need to set timeout for 3 seconds somehow, if can't write, code will continue...
write(fd_pipe, something, strlen(something));

// continue executing..

谢谢

最佳答案

就像网络套接字一样,您也可以在管道上使用 select() 来查看 write() 是否会阻塞。

首先,初始化fdset和超时:

fd_set fds;
FD_ZERO(&fds);
FD_SET(fd_pipe, &fds);
struct timeval tv = { 3, 0 }; // 3 secs, 0 usecs

以下调用最多等待 3 秒(如 tv 中指定),以便管道变为可写。

int st = select(fd_pipe+1, NULL, &fds, NULL, &tv);
if (st < 0) {
// select threw an error
perror("select");
else if (FD_ISSET(fd_pipe, &fds)) {
int bytes = write(fd_pipe, something, strlen(something));
} else {
// Writing not possible in 3 seconds, wait
}

当然,您必须检查 write() 调用的返回值(顺便说一句,在这两种情况下),因为写入的字节可能少于到管道。

关于c - Linux 管道的 write() 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60351931/

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