c - Linux 管道的 write() 超时

标签 c pipe

如何在 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/

相关文章:

c - 在 C 中,使用 TCP 套接字从读取调用中获取 0 意味着收到了 FIN?

Python 子进程 : Issues capturing error where part of command fail when piped together

c - 使用 fork() 产生内存映射

Code::Blocks :带有指针 FILE 参数的函数(和函数原型(prototype))出现错误

c - 我怎样才能知道 C 中接口(interface)的 IP 地址?

cmocka,如何检查函数指针

angular - 为什么我应该在 Angular 订阅中使用 select with pipe?

c - 结构数组中的内存分配

c++ - linux中管道之间的通信

linux - 从无尽的管道狂欢中阅读