Delete (unlink) or Create (fwrite) file with PHP when file is in use

被刻印的时光 ゝ 提交于 2019-12-11 19:39:40

问题


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.



来源:https://stackoverflow.com/questions/17591772/delete-unlink-or-create-fwrite-file-with-php-when-file-is-in-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!