Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

timeout on write() for linux pipe

Tags:

c

pipe

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

like image 541
jmp Avatar asked Aug 04 '26 02:08

jmp


1 Answers

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.

like image 64
Ctx Avatar answered Aug 05 '26 19:08

Ctx