views:

20

answers:

2

How to determine if I can write the given number of bytes to a filehandle (socket actually)? (Alternatively, how to "unread" the data I had read from other filehandle?)

I want something like:

n = how_much_can_I_write(w_handle);
n = read(r_handle, buf, n);
assert(n==write(w_handle, buf, n));

Both filehandles (r_handle and w_handle) have received ready status from epoll_wait.

I want all data from r_handle to be copied to w_handle without using a "write debt" buffer.

In general, how to copy the data from one filehandle to the other simply and reliably?

@related http://stackoverflow.com/questions/2677262/how-can-i-interconnect-two-sockets-in-linux

A: 

You can't do that - once the data is written, it's written - the operation is not reversible or predictable in advance. You need to rethink your program logic.

anon
There was no reversing of writing proposed. The reversing of reading was proposed as alternative solution (e.g. push the data back to some buffer in kernel).I think if kernel marks my filehandle as write-ready (in `epoll_wait`) then it knows how much can I write without danger of ending up blocked or written too few (and having to remember the rest somewhere).
Vi
A: 

I don't think there's any interface that allows you access to that information, and it would be stale as soon as you got it anyway.

I'd suggest setting both file descriptors to non-blocking, then reading/writing 1K (maybe larger) blocks until you get EAGAIN/EWOULDBLOCK, when you should cache one block until the next time the write fd is ready.

You need to have a buffer for doing the read/write cycle anyway, so keeping the buffer for the write-debt should be too much of a problem?

Douglas Leeder
Yes, all sockets are nonblocking. I want to prevent caching by not reading the read side if I'm not sure about writing. epoll_wait tells me when can I write, but I don't know how much I can write safely.
Vi