gpt4 book ai didi

php - 在 PHP 中的两个进程之间共享文件句柄是否安全?

转载 作者:搜寻专家 更新时间:2023-10-31 20:43:25 24 4
gpt4 key购买 nike

我找到了 similar questions在 Stack 上,但我不确定它们是否适用于 PHP。

我想用 pcntl_fork() 创建子进程.我想将来自父进程和子进程的消息写入日志文件。

如果我在父进程中打开一个文件句柄,从子进程写入同一个句柄是否安全?请注意,我只会附加到文件中。

我担心可能发生的竞争条件,特别是如果两个进程在不同的内核上执行:如果在两个不同内核上执行的两个进程同时写入同一个文件句柄会发生什么?

最佳答案

视情况使用flockstreamWrapper::stream_lockstream_set_blocking

flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows).

flock 作用于文件资源,如果 fclose() 会自动关闭,即使文件未解锁也是如此。

flock($fp, LOCK_EX);

您可以循环并等待文件准备好打开以进行写入,在我的例子中,我使用的是 c+

while(! $fp = @fopen($this->file, "c+")) {
if (time() - $time > $this->timeout)
throw new Exception("File can not be accessed");
usleep(100000);
}

$this->timeout 基本上是您结束等待文件的时间,可以找到一个很好的例子PHP issues using flock - file locking

关于php - 在 PHP 中的两个进程之间共享文件句柄是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16990409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com