Search code examples
executeshellexecutephp

PHP execute command as subcommand


I have the following 2 files and am executing them on linux (debian).

File1.php

<?php
exec("php -f file2.php > /dev/null 2>&1 &");
sleep(100);

File2.php

<?php
exec("sleep 30 > /dev/null 2>&1 &");
exec("sleep 30 > /dev/null 2>&1 &");
sleep(100);

The way it currently is it first starts file1.php and fires up file2.php and immediatly begins the sleep commands. It does not wait for the first sleep to finish to continue.

The problem is that the file2.php and sleep commands are not subcommands of file1.php and I can't simply kill it to kill all subcommands. My htop looks like this: http://dl.getdropbox.com/u/5910/Jing/2011-01-13_1611.png

I am searching for a way to have the commands be subcommands of file1.php so that I can easily kill them all :)

what I have:

'- php -f file2.php
'-sleep 30
'-sleep 30
'- php -f file1.php

basically I want this:

'- php -f file1.php
  '- php -f file2.php
    '-sleep 30
    '-sleep 30

Solution

  • popen and proc_open seem to do it :)

    file1.php

    <?php
    $descs = array(
       0 => array("pipe", "r"),
       1 => array("pipe", "w"),
       2 => array("file", "/tmp/error-output.txt", "a")
    );
    $process = proc_open("php -f file2.php", $descs, $pipess);
    sleep(100);
    

    file2.php

    <?php
    $desc = array(
       0 => array("pipe", "r"),
       1 => array("pipe", "w"),
       2 => array("file", "/tmp/error-output.txt", "a")
    );
    echo "asd";
    $process[] = proc_open("sleep 12", $desc, $pipes);
    echo "sleep!";
    $process[] = proc_open("sleep 10", $desc, $pipes);
    echo "asd";