Moony
Moony

Reputation: 97

fopen two processes

Is it ok to 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?

Upvotes: 1

Views: 2676

Answers (3)

Roger Pate
Roger Pate

Reputation:

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

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564413

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.

Upvotes: 1

Tim Sylvester
Tim Sylvester

Reputation: 23138

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

Upvotes: 1

Related Questions