PHP 进程/服务器崩溃时如何避免文件死锁?
我是 PHP 新手。我知道当两个用户到达同一个 php 文件并将内容添加到可锁定文件时,我可以使用 flock()
来锁定文件并避免竞争条件。
但是,如果 php 进程崩溃了怎么办?下一个等待可锁定文件的用户会发生什么?如果服务器崩溃(有人拔掉插头)会发生什么?锁会自动释放吗?重启服务器后文件会保持锁定状态吗?
简而言之,PHP 是否确保正确处理此类关键情况(即未显式释放锁)?如果不是,应该如何处理这些情况?如何从这些中恢复过来?
I am new to PHP. I understand I can use flock()
to lock a file and avoid race conditions when two users reach the same php file adding content to the lockable file.
However, what happens if a php process crashes? What happens to the next user waiting for the lockable file? What happens if the server crashes (someone pulls the plug)? Is the lock automatically released? Will the file remain locked after rebooting the server?
To make it short, does PHP make sure such critical situations (i.e., lock not explicitly released) are handled properly? If not, how should one deal with these situations? How to recover from these?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
锁由操作系统处理。因此:
PHP 不需要这样做除了使用操作系统提供的锁定文件的机制之外,还有什么特别的,所以一般来说你是完全安全的。
但是,如果您的网络服务器设置不是由新进程处理每个请求,那么如果一个请求异常终止(假设线程中止),锁将持续存在并阻止所有进一步的请求对于锁,很快就会导致 Web 服务器死锁。这是您真的、真的不应该使用在请求之间不提供进程级隔离的设置的众多原因之一(免责声明:我不是 Web 服务器专家 - 我可能在“不应该”方面是错误的)部分,尽管我对此表示怀疑)。
Locks are handled by the OS. Therefore:
PHP does not need to do anything special other than use the OS-provided mechanism for locking files, so in general you are perfectly safe.
However, if your web server setup is such that each request is not handled by a new process then if one request is abnormally terminated (let's say a thread is aborted) the lock will persist and block all further requests for the lock, quickly resulting in a deadlocked web server. That's one of the many reasons that you really, really should not use setups that do not provide process-level isolation among requests (disclaimer: I am not a web server expert -- I could be wrong in the "should not" part, even though I doubt it).