Delete (unlink) or Create (fwrite) file with PHP w

2019-08-17 00:51发布

问题:

I am running a website with a LAMP system.

Contents come from a database.

For caching purposes, I create files on my webserver (containing cachable contents) (via fwrite()).

Every once in a while I am deleting the cache files (via unlink()).

File creation and deletion is done with a cronjob.

My question is: what happens when a visitor to my website is currently browsing (=requesting from webserver) file A.php and I am trying to write to or delete this very same file A.php.

To be precise: what happens if my cronjob issues the unlink() command and at the same time serves the file to the user.

Will this create a race condition?

I know how to retrieve the status from unlink and fwrite operations, so could I just loop over my unlink/fwrite for as long as these function return false (could not be deleted/written)?

Looking forward to reading your opinions/answers!

回答1:

Yes, that obviously will create a race condition. The request for the file from the webserver and the deletion from the cron job are independent processes and there is no way for you to know if one or the other is doing something with the file.