Tuesday, September 29, 2009

Execute Shell Command in PHP without Waiting for Output

I wanted to execute a shell script from a PHP web app. However the shell script can take a long time to execute (possibly hours). I can't leave the browser waiting that long, so I tried getting around this:

I tried the following methods that do NOT work:

// back ticks?
`script`;
`script &`;
`nohup script &`;

// exec
exec('script');
exec('script &');
exec('nohup script &');

// system
system('script');
system('script &');
system('nohup script &');

// fork a child
$pid = pcntl_fork();
if($pid == 0) { system('nohup script &'); }


Finally determined a method that does work:
pclose(popen("nohup script &", 'r'));


My friend was surprised to learn of that one and told me what he uses, which also works (and looks a lot cleaner):
system('echo script | at now');