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

冷暖自知 提交于 2019-12-13 15:51:57

问题


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?


回答1:


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.




回答2:


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?



来源:https://stackoverflow.com/questions/2673975/determine-how-much-can-i-write-into-a-filehandle-copying-data-from-one-fh-to-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!