va************@gmail.com wrote:
I am writing a multithreaded web-server and multithreaded client in C.
The server is required to keep a log of the transactions in a local
file. I try to open a file using the following:
FILE *fd;
fd = fopen("file.log","w");
fprintf(fd, "%s\n",<a character string>);
This is done a by a thread in the server. Its a while(1) loop, so the
file never closes. The file "file.log" opens in the directory but never
writes anything into it.
Can anyone help?
The library and/or the operating system is probably
buffering the output you write to the file, accumulating
the data in memory until there's enough to make an actual
write worth while. If you wait until "enough" output has
been generated, it's likely that a whole bunch of data will
suddenly be written to the file all at once.
If you need to have the output committed to disk sooner,
there are at least two things to try:
- Use fflush(fd) after each output operation. This
tells the library to empty any buffers the file might
be using, sending their contents to the operating
system.
- Use setvbuf(fd, NULL, _IOLBF, BUFSIZ) immediately after
the fopen(). This tells the library to send data to the
operating system as soon as each line is completed (that
is, every time a '\n' character is written). For even
more immediacy (but perhaps less efficiency) you could
use _IONBF as the third argument.
Either of these will probably solve your problem. However,
there are no guarantees! Different platforms have different
I/O capabilities, and the C language Standard doesn't attempt
to regulate all their complexities. For example, you can be
sure that the library sends the data to the O/S, but you are
then at the mercy of whatever the O/S decides to do with it --
and this is a matter outside the scope of the C language. The
actions of fflush() and setvbuf() are "suggestions," really, not
commands. The suggestions are strong, but less than absolute.
--
Eric Sosman
es*****@acm-dot-org.invalid