Is it safe to share a file handle between two processes in PHP?

偶尔善良 提交于 2019-12-10 20:44:43

问题


I've found similar questions here on Stack but I'm not sure whether they apply to PHP.

I'd like to create child processes with pcntl_fork(). I want to write messages to a log file, from both the parent and the child processes.

If I open a file handle in the parent, is it safe to write to the same handle from the childs? Note that I will only be appending to the file.

I'm afraid of the race conditions that could happen, in particular if the two processes are executed on different cores: what would happen if two processes executing on two different cores were to write to the same file handle at the same time?


回答1:


Use flock or streamWrapper::stream_lock as the case may be or stream_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 works on file resource and is closed automatically if fclose() even if the file is not unlocked.

flock($fp, LOCK_EX);

You can loop and wait until the file is ready to be opened for writing in my case am using c+

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

$this->timeout is basically how long you ended to wait for the file a good example can be found PHP issues using flock - file locking



来源:https://stackoverflow.com/questions/16990409/is-it-safe-to-share-a-file-handle-between-two-processes-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!