Reputation: 430
I'm working on a simple chat server in C. In order to get incoming messages from all of my clients, I need to use the select
system call. I've decided I wanted to make use of the stdio
functions to make it easier, but I've concerned that the buffering of the library will mess up the use of select
(i.e data will remain buffered, read from the fd but not visible). What function should be used to multiplex buffered I/O in C?
As I was writing this, I remembered that file streams can be put into unbuffered mode. Would that work?
Upvotes: 3
Views: 276
Reputation: 155156
Unfortunately, unbuffered mode won't help. For example, fgets()
will want to read as much data as necessary until a whole line is read (or the user-provided buffer is filled up). To do this, it will call the underlying read()
more than once, even when unbuffered, and the calls after the first one will not be under your control. The same applies to fscanf()
and fprintf()
, and even to fread()
and fwrite()
.
If you really insist on using stdio, you can perform blocking IO in multiple threads, but that's not worth the trouble (and potential system overload). The only sane way to use multiplexed IO is to use the low-level reading operations to read the data, and then parse it using stdio tools such as sscanf
.
Upvotes: 3