Is it possible to have read not block, but write block for pipes? Is it possible to have read not block, but write block for pipes? unix unix

Is it possible to have read not block, but write block for pipes?


You surely can remove O_NONBLOCK flag before each write with fcntl and put it back after write completes. However, it seems better to keep the socket non-blocking all the time and to put write into a loop until it finishes. In order not to overload the CPU, put a select which will block the process until the socket is ready for write.

So, the writing code will look like:

int blockingWriteOnNonBlockingFd(int fd, char *buf, int size) {  fd_set wset, w;  int    n, r;  FD_ZERO(&wset);  FD_SET(fd, &wset);  n = 0;  while (n < size) {    w = wset;    select(fd+1, NULL, &w, NULL, NULL);    r = write(fd, buf+n, size-n);    if (r <= 0) {       if (r<0 && (errno == EWOULDBLOCK || errno == EAGAIN)) r = 0;       else { /* broken connection */ break; }    }    n += r;  }  return(n);}