spoulson
spoulson

Reputation: 21601

How to run a background process in PHP and read/write its stdout/stdin?

As an extension to question "php execute a background process":

Suppose I wanted to keep a process running during a PHP session, like an interactive bash shell. How can I establish redirection of stdout/stdin such that PHP can read/write to the process?

UPDATE: The key is to be able to kick off the process and keep it running in the background so that later requests can access its stdout/stdin streams.

Upvotes: 3

Views: 1954

Answers (3)

Iiridayn
Iiridayn

Reputation: 1821

If you're using Linux, you can access the proc file system at /proc. Though distributions may differ somewhat, in Ubuntu Server I can find my stdio at /proc/<pid>/fd/[012]. 0 is stdin, 1 is stdout, and 2 is stderr. This will probably not work if you are redirecting these from or to /dev/null, as some methods of spinning off long running background processes have you do. If you have access to the pid of the background process (a la http://nsaunders.wordpress.com/2007/01/12/running-a-background-process-in-php/), you should be able to access the stdin / stdout of the process in Linux.

Upvotes: 1

webbiedave
webbiedave

Reputation: 48887

If you're using PHP to relay user-typed commands to a shell, you can use mulitple calls to shell_exec

shell_exec will return the complete output which you can then echo back to the user.

Upvotes: 0

psmears
psmears

Reputation: 28090

I would use PHP Expect. The documentation has some very good usage examples.

Upvotes: 2

Related Questions