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

标签 php file-locking

我需要创建一个不能被其他脚本或进程删除的锁定文件。我试过这个:

    $f = fopen($pidFile, 'w');
    fwrite($f, getmypid());
    flock($f, LOCK_EX);

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

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

最佳答案

Linux 上的

flock 默认使用“建议锁定”,这意味着它不会阻止任何其他进程操作该文件。请参阅 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.

关于php - 如何针对外部进程锁定文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34392524/

相关文章:

PHP插入mysql数据库, 'WHERE field '等于我的选择

java - 如何在java中为属性文件提供文件锁?

java - 在 Java(TM) 平台 SE 二进制文件中打开

php - 当 DATE 即将到达当前日期等时将 DATE 设为粗体

php - js中的html表单验证

php - WordPress child 导航 a :current styling

php - PHP PDO 的 SQL 内部连接错误

java - 截断锁定文件

unix - 如何让人类和程序在不踩到对方脚趾的情况下访问同一个文件

java - WSO2 ESB 无法更新配置