如何在 PHP 中运行后台进程并读取/写入其 stdout/stdin?
作为问题“php执行后台进程”的扩展:
假设我想保留在 PHP 会话期间运行的进程,如交互式 bash shell。如何建立 stdout/stdin 重定向,以便 PHP 可以读取/写入进程?
更新:关键是能够启动进程并使其在后台运行,以便以后的请求可以访问其 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会使用 PHP Expect。该文档有一些非常好的使用示例。
I would use PHP Expect. The documentation has some very good usage examples.
如果您使用的是 Linux,则可以访问位于 /proc 的 proc 文件系统。尽管发行版可能有所不同,但在 Ubuntu Server 中,我可以在 /proc//fd/[012] 中找到我的 stdio。 0 是 stdin,1 是 stdout,2 是 stderr。如果您将它们重定向到 /dev/null 或将其重定向到 /dev/null,则这可能不起作用,因为您可以使用一些分离长时间运行的后台进程的方法。如果您有权访问后台进程的 pid(例如 http://nsaunders.wordpress.com/2007/01/12/running-a-background-process-in-php/),您应该能够访问标准输入/标准输出Linux 中的进程。
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.
如果您使用 PHP 将用户输入的命令中继到 shell,则可以多次调用 shell_exec
shell_exec 将返回完整的输出,然后您可以将其回显给用户。
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.