views:

558

answers:

2

I'm looking for the best, or any way really to start a process from php in the background so I can kill it later in the script.

Right now, I'm using: shell_exec($Command); The problem with this is it waits for the program to close.

I want something that will have the same effect as nohup when I execute the shell command. This will allow me to run the process in the background, so that later in the script it can be closed. I need to close it because this script will run on a regular basis and the program can't be open when this runs.

I've thought of generating a .bat file to run the command in the background, but even then, how do I kill the process later?

The code I've seen for linux is: $PID = shell_exec("nohup $Command > /dev/null & echo $!"); // Later on to kill it exec("kill -KILL $PID");

EDIT: Turns out I don't need to kill the process

+1  A: 

From the php manual for exec:

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

ie pipe the output into a file and php won't wait for it:

exec('myprog > output.txt');

From memory, I believe there is a control character that you can prepend (like you do with @) to the exec family of commands that also prevents execution from pausing - can't remember what it is though.

Edit Found it! On unix, programs executed with & prepended will run in the background. Sorry, doesn't help you much.

adam
I ended up using the batch file and doing:system("cmd /c C:[path to file]");That keeps the script going. Any ideas on how to kill the process? This actually opens up Adobe Reader, and I still need a way to close it before the script runs again.
William
Nevermind, turns out I don't need to kill the process. I can leave it running.
William
+2  A: 

Will this function from the PHP Manual help?

function runAsynchronously($path,$arguments) {
    $WshShell = new COM("WScript.Shell");
    $oShellLink = $WshShell->CreateShortcut("temp.lnk");
    $oShellLink->TargetPath = $path;
    $oShellLink->Arguments = $arguments;
    $oShellLink->WorkingDirectory = dirname($path);
    $oShellLink->WindowStyle = 1;
    $oShellLink->Save();
    $oExec = $WshShell->Run("temp.lnk", 7, false);
    unset($WshShell,$oShellLink,$oExec);
    unlink("temp.lnk");
}
Alix Axel
I ended up using (almost) this to launch a batch file and it works perfectly now.
William