views:

24

answers:

2

I have a unique problem. There are two processes (P0 and P1) trying to access one file. P0 is writing information to the file and P1 is reading the information. There is a race condition occurring between the two in which P1 is reading before P0 is finished writing. I have considered using Locks, Semaphores, etc. However, P1 exists in a set of code that I am not allowed to alter in any way, and it currently has no implementation to support the above proposed fixes.

Is there any way to remove this race condition without touching both sets of code?

A: 

You can let P0 write to file A and let P1 read from file B. When P0 has completed writing the file, rename file A to file B. You'll have to make sure the rename operation is atomic though.

Niels van der Rest
That was actually my temporary solution to the issue. It resolves much of the problem (its related to displaying an image onscreen), but elements of the issue persist. I suspect that the rename operation is not completely atomic. It is running on a Linux machine, which I have read is not completely compatible with the POSIX standard.
Mark
What happens if you delete B first and then rename A to B? Does P1 throw an error and exit?
Cahit
The program proceeds normally. I've noticed that deleting the non-temporary file has no affect on the conflict. P1 also happens to be web server code, which I have no way of even viewing. It could be that there are just too many unknown parameters in this issue.
Mark
A: 

Niels's solution is great, but may not be applicable if it's a big file with small deltas. I'm going to suggest that your solution would depend on:
a) whether P1 is locking the file and you just want to just get rid of the conflict,
b) whether you need to make sure that what P1 reads is always the updated copy with P0's changes, and
c) whether P1 honors a read-lock on the file in question.

Also, look for underlying O/S system calls to see if you can track P1's behavior from within P0 to coordinate the processes. For example, for Windows the .NET System.Diagnostics.Process class might provide some useful methods.

Cahit