1

I'm writing a C++ socket library to handle the intricacies of managing socket related system calls. I'm curious if there are any harmful side effects in creating a FILE* with fdopen(3) and using it alongside the client's original file descriptor.

I'd like to be able to do this because it provides greater flexibility in being able to use things such as select(2) while also using getline(3) (the primary goal of this question), however I fear that the FILE* will cause some issues with file descriptor based utilities (namely the internal buffering of a FILE* messing with select(2)'s ability to determine if there is data available for read(2)).

Clay Freeman
  • 533
  • 5
  • 17
  • see this: https://stackoverflow.com/questions/1589168/getline-over-a-socket – Sedat Kapanoglu May 10 '16 at 23:30
  • 4
    Here's what the standard says: [Interaction of File Descriptors and Standard I/O Streams](http://pubs.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_05.html#tag_02_05_01) – Mark Plotnick May 10 '16 at 23:37
  • @SedatKapanoglu The answers to this question don't really address the topic stated in the linked question; it merely warns against logical problems if such a function were to exist for a file descriptor. One of the answers did however suggest that keeping a custom buffer might be necessary for such functionality which is something that I'm not opposed to writing but doesn't address this question specifically. – Clay Freeman May 11 '16 at 00:03
  • @MarkPlotnick So would it be safe to use a `FILE*` and file descriptor simultaneously if I made the `FILE*` unbuffered? – Clay Freeman May 11 '16 at 00:09
  • @ClayFreeman if you only needed `FILE*` for "`getline`", the answer I pointed at says "don't -- not a good idea". that's why I shared it with you. – Sedat Kapanoglu May 11 '16 at 16:51
  • @ClayFreeman Probably, if you take care of this if necessary (and I don't think it'll be necessary if the fd is a socket, because that isn't seekable): *If the stream is open with a mode that allows reading and the underlying open file description refers to a device that is capable of seeking, the application shall either perform an fflush(), or the stream shall be closed.* – Mark Plotnick May 12 '16 at 21:18
  • In my tests on Linux with eglibc and on FreeBSD 10, `getline` on an unbuffered stream created from a socket called its `read`s with a *count* arg of 1, which is fine. But I think it's a good idea to test this on all your systems, to see whether `getline` will read beyond the end of a line. If it does, then as you say, it could throw off a subsequent `select`. – Mark Plotnick May 12 '16 at 21:18
  • @MarkPlotnick So essentially `getline` for an unbuffered stream would be just as inefficient as `fgetc` in a loop? I might as well just write my own buffer for this. – Clay Freeman May 12 '16 at 23:30
  • That sounds reasonable. – Mark Plotnick May 13 '16 at 00:52

0 Answers0