Avoid race conditions on file with differnet process

Keywords´╝Ü php file race-condition


Let's say i am writing this simple script:

if (file_exists($file)) {
    // read $file and do something

The problem is that what happens if another process deletes the file just after the check with file_exists was done? E.g.:

if (file_exists($file)) {
    // Some other process deletes $file right now 

    // read $file and do something --> GOES IN ERROR

How can you avoid this situation? Please note that you can't add a mutex since you can't modify the other process that are running on the systems

PS: i wrote PHP code, but this question is general to any programming language i believe