Is it safe to share a file handle between two proc

2019-07-02 03:19发布

问题:

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



标签: php fork