Hi,
--- Ursprüngliche Nachricht --- Von: Anders Johansson
An: suse-programming-e@suse.com Betreff: Re: [suse-programming-e] The meaning of atomic in write() Datum: Tue, 28 Mar 2006 20:04:06 +0200 The reason you only get output from one process at times is that one of the processes closes the file before the other one gets to write to it. You need to have a procedure in place for making sure that all files have finished writing before you call fclose
From my understanding, the second (child) process inherits its parent's file descriptor f. Therefore, both f in parent and child point to the same open-file structure (according to UNIX book). I thought that kernel reclaims an open-file structure only when it's not pointed anymore by descriptors?
If you had checked the return value of fprintf, you would have seen errors because the process is trying to write to a file that's closed. Always check return values. It's just good programming
Each call to fprintf will always success because it sends the string to a buffer allocated by C library (which is default to 8KB on my system). Because the string is less than 8KB, fprintf() does not causes in write(). The write() is issued only during fclose(), and I've confirmed this with strace. I've modified the program to assert(fclose(f) == 0) (and assert(fprintf >= 0) just to make sure). But still, I get the same result: even if only one process succesfully writes, no assertion is violated. In the beginning I thought that this would not happen due to write() atomicity, just as Anders said. This means, the second write() continues writing from the offset after the first write(), resulting in test.txt to contains strings from both processes. If test.txt contains only strings of one process, this implies that write() is not atomic because both they are "overlap" (somehow to start writing from beginning of file). Earlier, Steve mentioned that the atomicity is valid only for FIFO or pipe. But I remembered vaguely from a newsgroup thread that the atomicity also holds for file? I realizes that the "text-book" solution is to lock the file before writing. Initially this program is just to show the effect of user-level I/O buffering by C library. But now I become more curious on this concurrent file access. -- Regards, Verdi -- Bis zu 70% Ihrer Onlinekosten sparen: GMX SmartSurfer! Kostenlos downloaden: http://www.gmx.net/de/go/smartsurfer