Determine how much can I write into a filehandle; copying data from one FH to the other
Asked Answered
A

2

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 How can I "interconnect" two sockets in Linux?

Acedia answered 20/4, 2010 at 9:37 Comment(0)
H
0

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.

Honeycomb answered 20/4, 2010 at 9:40 Comment(1)
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).Acedia
K
0

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?

Kiley answered 20/4, 2010 at 10:6 Comment(1)
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.Acedia

© 2022 - 2024 — McMap. All rights reserved.