开发者

fopen two processes

开发者 https://www.devze.com 2022-12-13 16:27 出处:网络
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.

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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消