Skip to main content
 首页 » 编程设计

php之重命名 PHP 不断写入的文件是否安全

2025年01月19日34mayingbao

PHP 以 "a" 模式不断地将文本附加到文件 foo.log。我想在 python 中读取 foo.log 的内容并截断已读取的行,同时避免 python 和 PHP 之间的并发访问问题。

This answer声明 os.rename 在大多数平台上是原子的。因此,通过简单地将 foo.log 重命名为 bar.log 然后将 bar.log 读入 python 来实现我的目标是否安全?或者我是否需要实现更复杂的解决方案,例如共享锁文件?

请您参考如下方法:

如果您fopen 可能不会。我用的日志是

file_put_contents( $filename, $data, FILE_APPEND|LOCK_EX); 

这样你就没有打开的资源句柄,如果不存在,它将在写入时创建一个文件。

我用 fwrite 尝试过一次,大约 15 个不同的进程都记录了所有的东西,结果里面有半个 NUL 垃圾文件。于是我开始使用它。

http://php.net/manual/en/function.file-put-contents.php

  • FILE_USE_INCLUDE_PATH Search for filename in the include directory. See include_path for more information.

  • FILE_APPEND If file filename already exists, append the data to the file instead of overwriting it.

  • LOCK_EX Acquire an exclusive lock on the file while proceeding to the writing. In other words, a flock() call happens between the fopen() call and the fwrite() call. This is not identical to an fopen() call with mode "x".