douchi5822
2014-07-20 03:47
浏览 87
已采纳

从PHP脚本在后台使用&&执行多个linux命令

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.

图片转代码服务由CSDN问答提供 功能建议

好的,所以我有一个操作系统Ubuntu。 我有灯泡。 现在我想在后台执行一些命令,这将至少执行10-15分钟。 我想从Web界面而不是cli从PHP脚本执行此命令。

第一个实例:

当我这样做时 这个,php脚本能够成功地在后台运行命令:

  command1&amp;&gt;  / dev / null&amp; 
   
 
 

第二个实例:

但是当我这样做时:

  command1&amp;&gt;  / dev / null&amp;&amp;  command2&amp; 
   
 
 

然后命令不在后台运行,php脚本暂停,直到执行此命令。 我希望在command1完成后执行command2,以便我(或我的php脚本)可以知道command1已经执行。 但它应该在后台,否则我的PHP脚本不会按时执行。

当我从命令行执行第二个实例时,它可以在后台运行,但是当我这样做时 它来自PHP脚本然后它无法在后台运行。

我使用php的exec函数来执行这些命令。

 &lt;?php 
exec('command1&amp;&gt; / dev / null&amp;&amp; command2&amp;',$ out,$ ret); 
?&gt; 
   \  n 
 

我们将不胜感激。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dongshui2254 2014-07-20 04:08
    最佳回答

    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 &&.

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题