Invoke external shell script from PHP and send som

2019-04-16 01:09发布

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).

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? 

标签: php shell
2条回答
Rolldiameter
2楼-- · 2019-04-16 02:04

You need to use proc_open() to be able to communicate with your process. 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);
查看更多
Explosion°爆炸
3楼-- · 2019-04-16 02:04

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.

What you can do instead is use signals. Virtually all shell applications respond to signals like SIGTERM and SIGHUP. It is possible to trap and handle these signals as well using shell scripts. If you use proc_open() to start your shell script then you can use proc_terminate() to send a SIGTERM signal.

查看更多
登录 后发表回答