What should I call Linux dup2 with PHP?

Unfortunately, I found that all solutions for running external programs are not suitable, so I use my own implementation, which is pcntl_execafter pcntl_fork.

But now I need to redirect the stderr / stdout of the executable to some file. Obviously, I have to use some kind of dup2Linux call after pcntl_fork, but the only one dup2that I see in PHP is eio_dup2that it looks like it doesn’t work with regular threads (like stderr / stdout), but with some asynchronous threads.

How can I call dup2from PHP or how can I redirect std * without it?

There are no answers to this question (although without details): How to call the dup2 () system call from PHP?

+4
source share
1 answer

Here goes the way unnecessarily dup2. It is based on this answer .

$pid = pcntl_fork();

switch($pid) {

    case 0:
        // Standard streams (stdin, stdout, stderr) are inherited from
        // parent to child process. We need to close and re-open stdout 
        // before calling pcntl_exec()

        // Close STDOUT
        fclose(STDOUT);

        // Open a new file descriptor. It will be stdout since 
        // stdout has been closed before and 1 is the lowest free
        // file descriptor
        $new_stdout = fopen("test.out", "w");

        // Now exec the child. It output goes to test.out
        pcntl_exec('/bin/ls');

        // If `pcntl_exec()` succeeds we should not enter this line. However,
        // since we have omitted error checking (see below) it is a good idea
        // to keep the break statement
        break; 

    case -1: 
        echo "error:fork()\n";
        exit(1);

    default:
        echo "Started child $pid\n";
}

Error handling has been omitted for brevity. But keep in mind that in system programming, any return value of a function should be carefully handled.

+4
source

All Articles