Skip to content
Advertisement

Execute background external program

If I have a script like this:

<?php
system('notepad');
echo "ENDn";

It opens the Notepad program, but the script stops until Notepad is ended. I would like to open the program in the background. I tried this:

system('notepad &');

but it the process continues to block the script. I think its because my shell is PowerShell, not Bash or similar. Is this possible to do?

Advertisement

Answer

As a workaround, you can use proc_open:

<?php
$a_desc = [];
$a_pipe = [];
$r = proc_open('notepad', $a_desc, $a_pipe);
echo "ENDn";
proc_close($r);

When you use proc_open, PHP will only wait for the process to terminate if you also call proc_close. So in the above script, the END will go ahead and print, but the script will still hang after that. If you want to totally forget about the process, you can omit the proc_close:

<?php
$a_desc = [];
$a_pipe = [];
proc_open('notepad', $a_desc, $a_pipe);
echo "ENDn";

In general you want to call proc_close, as if your external command produces output, then that output would likely print after any internal echo statements you have.

https://php.net/function.proc-close

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement