PHP.mk документација

posix_mkfifo

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.posix-mkfifo.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.posix-mkfifo.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
posix_mkfifo

Референца за `function.posix-mkfifo.php` со подобрена типографија и навигација.

function.posix-mkfifo.php

posix_mkfifo

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_mkfifoСоздајте специјална FIFO датотека (именувана цевка)

= NULL

posix_mkfifo(string $filename, int $permissions): bool

posix_mkfifo() креира специјална FIFO датотека која постои во датотечниот систем и делува како двонасочна комуникациска крајна точка за процесите.

Параметри

filename

Патот до FIFO file.

permissions

Вториот параметар permissions мора да биде даден во октална нотација (на пр. 0644). Дозволата на новосоздадената FIFO исто така зависи од поставката на тековната umask(). The permissions of the created file are (mode & ~umask).

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.

Белешки од корисници Управување со PDO конекции

tim
пред 17 години
For non-blocking, fopen'd read access to a "half-connected" pipe (created with /usr/bin/mkfifo, posix_mkfifo, etc.), I just go ahead and do:
<?php
  $fh=fopen($fifo, "r+"); // ensures at least one writer (us) so will be non-blocking
  stream_set_blocking($fh, false); // prevent fread / fwrite blocking
?>

The "r+" allows fopen to return immediately regardless of external  writer channel.  You then have to use your own conventions to track $fh as a pseudo-read-only resource, since fwrite would technically be permitted as well.  I've successfully used this approach on Linux with PHP 4.3.10 and PHP 5.2.4 with both half-connected (no writer yet) and pre-connected (writer already waiting) pipes, polling with stream_select as usual.
TorokAlpar на Gmail точка com
пред 17 години
Here is a possible solution to what  - tech at kwur dot com- mentioned:

 I faced the problem where i had a process (a server) that needed to take care of socket connection, and in the meanwhile get some data from the database. I didn't wanted to make the clients wait for the query execution time, so i decided to make a separate process that executes the query on the DB, and the two would communicate over a pipe. Of course i didn't wanted the server blocking if no data was available. So what i come up with is to use stream_select() , and to overcome the mentioned problem, i would fork the process, open up the pipe for writing in the child, this way the parent won't block when it opens the pipe.

here is some code 

<code>

<?php

if (pcntl_fork() == 0)
{
    // kid
    $file = fopen("JobsQueue","w");
    sleep(1);
    exit(0);   
}
else
{
    usleep(15); // make sure that the child executes first
    $file = fopen("JobsQueue","r");
}

 echo "opened the queue \n";
 
 while (true)
 {
     $reders = array($file);
     if (stream_select($reders,$writers=null,$except=null,0,15) < 1)
     {
         continue;
     }
     else
     {
         // read data from the fifo
         $data = fread($file,1024);
         echo $data;
     }          
     sleep(1);
 }

?>

</code>
Enric Jaen
пред 18 години
A way to have a non-blocking pipe reader is to check first if the pipe exists. If so, then read from the pipe, otherwise do other stuff. This will work assuming that the writer creates the pipe, writes on it, and after that deletes the pipe.

This is a blocking writer:

<?php
   $pipe="/tmp/pipe";
   $mode=0600;
   if(!file_exists($pipe)) {
      // create the pipe
      umask(0);
      posix_mkfifo($pipe,$mode);
   }
   $f = fopen($pipe,"w");
   fwrite($f,"hello");  //block until there is a reader
   unlink($pipe); //delete pipe

?>

And this is the non-blocking reader:

<?php
   $pipe="/tmp/pipe";
   if(!file_exists($pipe)) {
      echo "I am not blocked!";
   }
   else {
      //block and read from the pipe
      $f = fopen($pipe,"r");
      echo fread($f,10);
   }
?>
tech на kwur точка com
пред 18 години
This is still not a solution: if I listen to commands on a pipe and output status on a separate pipe, PHP will block on both opens because something else has not already connected to this pipe.  Because I can't do a low-level fcntl() to to set O_NONBLOCK or something like it, this always locks up and is really stupid.  The only way I can get it to work is to spawn seperate subshells with system() and have them cat, or echo respectively and then the pipes work properly...usually?  Its alot of trouble that we can't set the blocking on the open!!
Uther Pendragon
пред 18 години
Note (quoted from `man 7 pipe` on debian linux):

"On some systems (but not Linux), pipes are bidirectional:  data  can  be  transmitted  in  both directions  between  the pipe ends.  According to POSIX.1-2001, pipes only need to be unidirectional.  Portable applications should avoid reliance on bidirectional pipe semantics."

Linux pipes are NOT bidirectional.

Also, it appears to me that the use of fifo (named) pipes in php is pretty pointless as there appears to be NO way of determining whether opening (let alone reading) from it will block.  stream_select SHOULD be able to accomplish this, unfortunatly you cannot get to this point because even trying to OPEN a pipe for read will block until there is a writer.

I even tried to use popen("cat $name_of_pipe", 'r'), and even it blocked until it was opened for write by another process.
Mauro Titimoli
пред 16 години
Object Oriented FIFO Communication process:

<?php
interface Communication {
    public function receive($bytes = 1024);

    public function getData();

    public function clearData();

    public function send($data);
}

class FIFOCommunication implements Communication {
    private $fifos;

    private $data;

    static public function stream_fifo_open($fifoPath, $mode) {
        if (pcntl_fork() == 0) {
            if (! file_exists($fifoPath)) {
                posix_mkfifo($fifoPath, $mode);
            }

            $fifo = fopen($fifoPath, 'w');
            sleep(1);

            exit(0);
        }
        else {
            usleep(15);

            return fopen($fifoPath, 'r');
        }
    }

    static public function stream_fifo_write($fifoPath, $mode, $data) {
        if (pcntl_fork() == 0) {
            if (! file_exists($fifoPath)) {
                posix_mkfifo($fifoPath, $mode);
            }

            $fifo = fopen($fifoPath, 'w');

            fwrite($fifo, $data);

            exit(0);
        }
    }

    public function __construct(
        $fifoInputName, $fifoInputMode,
        $fifoOutputName, $fifoOutputMode
    ) {
        $this->fifos = array(
            'input' => array(
                'file' => self::stream_fifo_open($fifoInputName, $fifoInputMode),
                'mode' => $fifoInputMode,
                'name' => $fifoInputName,
                'use' => 'r',
            ),
            'output' => array(
                'mode' => $fifoOutputMode,
                'name' => $fifoOutputName,
                'use' => 'w'
            )
        );
    }
    public function remove($type = null) {
        switch ($type) {
            case 'input':
                @unlink($this->fifos['input']['name']);
                break;

            case 'output':
                @unlink($this->fifos['output']['name']);
                break;

            default:
                @unlink($this->fifos['input']['name']);
                @unlink($this->fifos['output']['name']);
        }
    }

    public function receive($bytes = 1024) {
        $readers = array($this->fifos['input']['file']);
        if (stream_select($readers, $writers = null, $except = null, 0, 15) == 1) {
            $data = fread($this->fifos['input']['file'], $bytes);
        }

        if (! empty($data)) {
            $this->data .= $data;
            return true;
        }
        else {
            return false;
        }
    }

    public function getData() {
        return $this->data;
    }

    public function clearData() {
        $this->data = null;
    }

    public function send($data) {
        $fifoOutput = & $this->fifos['output'];
        self::stream_fifo_write($fifoOutput['name'], $fifoOutput['mode'], $data);
    }
}

$fifoCommunication = new FIFOCommunication(
    getmypid() . '.input', 0600,
    getmypid() . '.output', 0600
);

echo "COMMUNICATION STARTED\n";

while (true) {
    if ($fifoCommunication->receive()) {
        $data = $fifoCommunication->getData();
        if ($data == "EXIT\n") {
            break;
        }
        else {
            $fifoCommunication->send('RECEIVED: ' . $fifoCommunication->getData());
        }
    }

    sleep(1);
}

$fifoComunication->remove();
?>
mike на easystyle точка org
пред 17 години
Couldn't you just open up a writer yourself right after you open up a reader?  Just to be sure that you won't have any blocking issues...
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.