简体   繁体   English

从PHP调用外部shell脚本并向其发送一些输入

[英]Invoke external shell script from PHP and send some input to it

my aim is to invoke a shell script from a PHP program and then wait for a few seconds to send some termination key to it (I can't simply kill it because I want to test the correct execution of the termination phase). 我的目的是从PHP程序中调用Shell脚本,然后等待几秒钟向它发送一些终止密钥(我不能简单地杀死它,因为我想测试终止阶段的正确执行)。

Here is an example of what I'd like to have: 这是我想要的示例:

system( "RUNMYSCRIPT.sh" );  // Launch the script and return immediately.
sleep( 10 );                 // Wait.
exec( "q" );                 // Send a termination key to the previous script? 

You need to use proc_open() to be able to communicate with your process. 您需要使用proc_open()才能与您的进程进行通信。 Your example would work like this: 您的示例将如下所示:

// How to connect to the process
$descriptorspec = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w")
);

// Create connection
$process = proc_open("RUNMYSCRIPT.sh", $descriptorspec, $pipes);
if (!is_resource($process)) {
    die ('Could not execute RUNMYSCRIPT');
}

// Sleep & send something to it:
sleep(10);
fwrite($pipes[0], 'q');

// You can read the output through the handle $pipes[1].
// Reading 1 byte looks like this:
$result = fread($pipes[1], 1);

// Close the connection to the process
// This most likely causes the process to stop, depending on its signal handlers
proc_close($process);

You can't simply send a key event to such an external application. 您不能简单地将按键事件发送到此类外部应用程序。 It is possible to write to the stdin of an external shell script by using proc_open() instead of system(), but most shell scripts listen for keystrokes directly instead of watching stdin. 可以使用proc_open()而不是system()来写入外部Shell脚本的stdin,但是大多数Shell脚本直接侦听击键而不是看stdin。

What you can do instead is use signals. 相反,您可以使用信号。 Virtually all shell applications respond to signals like SIGTERM and SIGHUP. 几乎所有外壳程序应用程序都会响应SIGTERM和SIGHUP等信号。 It is possible to trap and handle these signals as well using shell scripts. 也可以使用Shell脚本捕获和处理这些信号。 If you use proc_open() to start your shell script then you can use proc_terminate() to send a SIGTERM signal. 如果使用proc_open()启动Shell脚本,则可以使用proc_terminate()发送SIGTERM信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM