php – 如何针对外部进程锁定文件

前端之家收集整理的这篇文章主要介绍了php – 如何针对外部进程锁定文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要创建一个无法被其他脚本或进程删除的锁文件.我试过这个:
$f = fopen($pidFile,'w');
    fwrite($f,getmypid());
    flock($f,LOCK_EX);

但是,从当前用户启动的任何其他进程都可以删除$f文件,即使正在运行的脚本仍然打开了文件句柄.如何解决这个问题并防止其他人(即非PHP进程)删除文件?并且当进程退出时锁会自动释放?所有类似的问题都以RTM flock()结束,但它们都没有回答如何针对外部进程锁定文件.

操作系统是Linux 2.6.32-431.el6.x86_64

flock on Linux默认使用“顾问锁定”,这意味着它不会阻止任何其他进程操纵该文件.请参阅PHP手册中的注释.

flock() uses mandatory locking instead of advisory locking on Windows. Mandatory locking is also supported on Linux and System V based operating systems via the usual mechanism supported by the fcntl() system call: that is,if the file in question has the setgid permission bit set and the group execution bit cleared. On Linux,the file system will also need to be mounted with the mand option for this to work.

另见https://www.kernel.org/doc/Documentation/filesystems/mandatory-locking.txt

A file is marked as a candidate for mandatory locking by setting the group-id bit in its file mode but removing the group-execute bit. This is an otherwise
meaningless combination,and was chosen by the System V implementors so as not
to break existing user programs.

Note that the group-id bit is usually automatically cleared by the kernel when
a setgid file is written to. This is a security measure. The kernel has been
modified to recognize the special case of a mandatory lock candidate and to
refrain from clearing this bit. Similarly the kernel has been modified not
to run mandatory lock candidates with setgid privileges.

还要注意警告:

Not even root can override a mandatory lock,so runaway processes can wreak havoc if they lock crucial files. The way around it is to change the file permissions (remove the setgid bit) before trying to read or write to it.

原文链接:https://www.f2er.com/php/134403.html

猜你在找的PHP相关文章