简体   繁体   English

linux 管道的 write() 超时

[英]timeout on write() for linux pipe

How can I set timeout for write() on linux pipe ?如何在 linux 管道上为 write() 设置超时?

example code:示例代码:

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..

thanks谢谢

Just as for network sockets you can use select() also on pipes to see, if a write() would block.就像网络套接字一样,您也可以在管道上使用select()来查看write()是否会阻塞。

First, initialize the fdset and the timeout:首先,初始化 fdset 和超时时间:

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

The following call waits at maximum 3 seconds (as specified in tv ) for the pipe to become writable.以下调用最多等待 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
}

You have of course to check the return value of the write() call (in both cases btw), because it might happen that less bytes than requested were written to the pipe.您当然必须检查write()调用的返回值write()顺便说一下,在这两种情况下),因为写入管道的字节数可能少于请求的字节数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM