How to use named pipes in PHP between different functions or even different processes without fork?

后端 未结 3 1512
一向
一向 2021-01-13 14:34

I want to write an Ajax web application, a game to be specific. Two web clients have to communicate with each other via the PHP server. My approach to solve this is to use A

相关标签:
3条回答
  • 2021-01-13 15:14

    When you use the pipes in separate functions like this, the write pipe A would seem to be closed/discarded again (local scope of $pipeA). The assumption would be that the pipe must be opened for reading and/or writing in order to retain any info, which makes sense really. Though I don't know the inner magic.

    You can also observe that your blocking read-call succeeds when you feed the pipe from another process (like echo magic >> testpipe). So you'd already have step 2 done, but you need some pipehandle management.

    If you change it as follows it'd work:

        private $pipeA;
        public function writePipe_test(){
            $this->pipeA = fopen("testpipe",'r+');
            fwrite($this->pipeA, 'ABCD');
        }
    

    Edit: or setting $pipeA to have global scope, for that matter..

    0 讨论(0)
  • 2021-01-13 15:16

    Just a short statement, that I actually found a nice solution using named pipes:

    public function createPipe_test(){
        posix_mkfifo("testpipe", 0777);
    }
    
    public function writePipe_test($value){
        $pipeA = fopen("testpipe",'w');
        $valueString = number_format($value);
        $valueLen = number_format(strlen($valueString));
        fwrite($pipeA, $valueLen);
        fwrite($pipeA, $valueString);
    }
    
    public function readPipe_test(){
        $pipeB = fopen("testpipe",'r');
        $valueLen = fread($pipeB, 1);
        return fread($pipeB, $valueLen);
    }
    

    I have two processes.

    If process 1 calls writePipe_test(), then it waits until process 2 calls readPipe_test() to read the data out of the pipe.

    If process 1 calls readPipe_test(), then it waits until process 2 calls writePipe_test() to write something into the pipe.

    The trick is 'w' and 'r' instead of 'r+'.

    0 讨论(0)
  • 2021-01-13 15:21

    Im not sure wether I understand your 2nd last post..

    But to comment on the last one, if I don't misunderstand, TCP might be even more complex because you will have to establish a connection before you can either read or write, so youve got different overhead

    As for the pipehandle closing at the function end, I assume you'll face the same problem with the sockets; but the pipefile remains!

    Persistent storage (files,db) would make the clients independent timingwise, if you want to use blocking calls then files might actually be a way to go..

    0 讨论(0)
提交回复
热议问题