简体   繁体   中英

Executing multiple linux commands using && in background from a PHP script

Ok so I have a operating system Ubuntu. I have lampp. Now I wanna execute some command in the background which is going to take atleast 10-15 minutes to execute. I want to execute this command from PHP script from web interface not cli.

First Instance:

When I do this , the php script is successfully able to run the command in the background:

command1 &> /dev/null &

Second Instance:

But when I do this:

command1 &> /dev/null && command2 &

,

Then the command does not run in background, the php script pauses until this command executes. I want the command2 to execute after command1 is completed so that I (or my php script) can know that command1 has been executed. But it should be in background else my php script doesn't execute on time.

When I do the second instance from command line, it is able to run in background, but when I do it from php script then it is unable to run in background.

I am using the exec function of php to execute those commands.

<?php
exec('command1 &> /dev/null && command2 &',$out,$ret);
?>

Any help would be appreciated.

Try this:

<?php
exec('(command1 && command2) >/dev/null &',$out,$ret);

What it's doing is launching your commands in a subshell so that command1 runs first and then command2 only runs after command1 completes successfully, then redirects all the output to dev/null and runs the whole thing in the background.

If you want to run command2 regardless of the exit code of command1 use ; instead of && .

The computer is doing what you're instructing it to do. The && list operator tells the shell to only run the second command if the first command completes successfully. Instead, you should run two independent commands; if there really is a dependency between the two commands, then you may need to reconsider your approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM