微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返回预支付订单号的接口,目前微信支付所有场景均使用这一接口。下面介绍的是其中NATIVE的支付实现流程与PC端实现扫码支付流程
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返回预支付订单号的接口,目前微信支付所有场景均使用这一接口。下面介绍的是其中APP的支付的配置与实现流程
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户信息这个功能的开发流程。 配置 1.首先得在微信公众平台申请一下微信小程序账号并获取到小程序的AppID和AppSecret https://mp.weixin.qq.com/cgi-bin/loginpage?url=%2Fwxamp%2F
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一款开源且免费商用的后台开发框架,它基于ThinkPHP和Bootstrap两大主流技术构建的极速后台开发框架,它有着非常完善且强大的功能和便捷的开发体验,使我逐渐喜欢上了它。
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛,就离不开通讯了,然后我就想到了长连接。这里本人用的是GatewayWorker框架。
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返回预支付订单号的接口,目前微信支付所有场景均使用这一接口。下面介绍的是其中JSAPI的支付实现流程
服务器优化必备:深入了解PHP8底层开发原理
Golang的网络编程:如何快速构建高性能的网络应用?
Golang和其他编程语言的对比:为什么它的开发效率更高?
PHP8底层开发原理揭秘:如何利用新特性创建出色的Web应用