fopen two processes
Is it ok t开发者_StackOverflowo have two processes writing to same file multiple times in a certain span of time usign fopen(append mode), fprintf, fclose functionality. they wait for data and repeat the open,write,close operation.
is there a chance of data not being written?
If your two processes are accessing the same file, you should use a Mutex to prevent both processes from writing to the file at the same time.
The link above is for Windows platforms. For other platforms, you'll need the platform's appropriate construct, such as a pthreads mutex created with PTHREAD_PROCESS_SHARED
.
The fopen()
function opens the file with no sharing protections (SH_DENYNO
), at least on Win32/VC++, so without some kind of locking protocol you'll potentially corrupt the file.
If your app is Win32 you can use the CreateFile
API to specify sharing modes. The _fsopen()
function is somewhat more portable, but not as portable as fopen()
.
If you're not on Windows, the easiest way among cooperating processes is to use flock. (Use fdopen to get a FILE from a fd.)
精彩评论