views:

523

answers:

2

Hi All, 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?
+2  A: 

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
$descriptors = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w")
);

// Create connection
$process = proc_open("RUNMYSCRIPT.sh", $descriptors, $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);
soulmerge
A: 

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.

Sander Marechal