我知道file_put_contents()使得在 PHP 中将数据附加到文件变得非常容易。我想尝试使用 PHP“threads”将 file_put_contents()
用于来自不同 PHP 线程的同一日志文件。从不同的 PHP 线程对同一个文件运行 file_put_contents() 是否存在风险,或者如果文件被锁定或被另一个线程访问,这些线程是否会愉快地阻塞?
编辑:发现a similar question推荐flock() ,但风险问题似乎并未得到充分解决。这些是“原子”写操作吗?
最佳答案
正如手册页上所说(您提供了链接!):
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
使用LOCK_EX
标志来防止双重写入
关于php - 在来自不同 PHP 线程的同一文件上运行 file_put_contents() 是否存在风险?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5479580/