How can I set timeout for write() on linux pipe ?
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.
First, initialize the fdset and the timeout:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With