Hi,

I've just committed my first bash at a bi-directional (and more) process
pipe function.  It also appears to work on Win32 (I've only done minimal
testing).

The rationale, besides allowing reading and writing to a spawned process,
is that redirecting the standard streams becomes more portable/shell
independent.  The example below is roughly equivalent to something
like this in unix shell speak:

output=$(echo "hello my child" | cat - 2>/path/to/file)

but will also work under win32.

Heres the synopsis:

$descriptorspec = array(
  0 => array("pipe", "r"), /* stdin for child is a readable pipe */
  1 => array("pipe", "w"), /* stdout for child is a writeable pipe */
  2 => array("file", "/path/to/file", "w"), /* stderr is a writeable file */
);

$command = "cat -";

// $handles is passed by reference
$process = proc_open($command, $descriptorspec, $handles);
// $process is a resource representing the child process
// $handles is an array indexed by integer which holds file
// handles for the parent side of any pipes passed to the child

/* send some text to stdin of child */
fwrite($handles[0], "hello my child");
fclose($handles[0]);

/* read all of the child stdout and display it */
fpassthru($handles[1]);
fclose($handles[1]);

// Although I'm using pclose to release $process here,
// $process cannot be used with fread() etc.
// I intend to have a proc_close function or alias.
// I haven't implemented the return value fetching under win32 yet.
$return_value = pclose($process);

The $descriptorspec array is not limited to descriptors 0-3; any integer
index file descriptor number can be passed.  This should also work under
win32, although win32 only really respects stdin/stdout/stderr - passing
and using other descriptors should be possible by passing the win32 handle
as an integer argument on the command line.  We don't currently have a
means to do this from PHP user-space; if anyone has suggestions on a nice
way of doing this (perhaps using a simple sprintf-style expansion on the
command string), please let me know.

$descriptorspec can also accept PHP file handles as the array values,
provided that the underlying stream can be cast into a file descriptor.
Also, file based descriptors will try to open(2) the path before attempting
to use URL wrappers (if enabled), which should save some time/memory overhead
since files and pipes should be the most common usage.

Also TODO is "2>&1" style syntax.

Any feedback/comments are more than welcome,

--Wez.


-- 
PHP Development Mailing List <http://www.php.net/>
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to