Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't use C standard I/O with sockets

It's often said that one shouldn't use C standard I/O functions (like fprintf(), fscanf()) when working with sockets.

I can't understand why. I think if the reason was just in their buffered nature, one could just flush the output buffer each time he outputs, right?

Why everyone uses UNIX I/O functions instead? Are there any situations when the use of standard C functions is appropriate and correct?

like image 393
dmitru Avatar asked Dec 12 '22 23:12

dmitru


2 Answers

You can certainly use stdio with sockets. You can even write a program that uses nothing but stdin and stdout, run it from inetd (which provides a socket on STDIN_FILENO and STDOUT_FILENO), and it works even though it doesn't contain any socket code at all.

What you can't do is mix buffered I/O with select or poll because there is no fselect or fpoll working on FILE *'s and you can't even implement one yourself because there's no standard way of querying a FILE * to find out whether its input buffer is empty.

As soon as you need to handle multiple connections, stdio is not good enough.

like image 146
Alan Curry Avatar answered Dec 29 '22 18:12

Alan Curry


It's totally fine when you have simple scenario with one socket in blocking mode and your application protocol is text-based.

It quickly becomes a huge pain with more then one or non-blocking socket(s), with any sort of binary encoding, and with any real performance requirements.

like image 33
Nikolai Fetissov Avatar answered Dec 29 '22 17:12

Nikolai Fetissov