2012-09-28 53 views
2

我使用PHP中的exec函數來運行命令。我運行的命令通常需要很長時間,我不需要讀取它的輸出。是否有一種簡單的方式告訴PHP在繼續執行腳本的其餘部分之前不要等待exec命令完成?如何在調用exec()後強制PHP腳本繼續使用腳本?

+0

也許它是作爲一個單獨的過程嗎? – tradyblix

+0

我該怎麼做呢?我只是將'&'追加到命令的末尾? –

+1

'exec(「nohup $ your_command&」)' - 運行命令免於hangups,輸出到非tty('nohup'),在後臺運行('&') – Nemoden

回答

2
// nohup_test.php: 

// a very long running process 
$command = 'tail -f /dev/null'; 
exec("nohup $command >/dev/null 2>/dev/null &"); // here we go 
printf('run command: %s'.PHP_EOL, $command); 
echo 'Continuing to execute the rest of this script instructions'.PHP_EOL; 

for ($x=1000000;$x-->0;) { 
    for ($y=1000000;$y-->0;) { 
    //this is so long, so I can do ps auwx | grep php while it's running and see whether $command run in separate process 
    } 
} 

運行nohup_test.php:

$ php nohup_test.php 
run command: tail -f /dev/null 
Continuing to execute the rest of this script instructions 

讓我們來看看我們的流程的PID:

$ ps auwx | grep tail 
nemoden 3397 0.0 0.0 3252 636 pts/8 S+ 18:41 0:00 tail -f /dev/null 
$ ps auwx | grep php 
nemoden 3394 82.0 0.2 31208 6804 pts/8 R+ 18:41 0:04 php nohup_test.php 

,你可以看到,PID是不同的,我的腳本,而無需等待tail -f /dev/null運行。

+0

這太棒了。謝謝! –

+0

不用客氣:) – Nemoden

+0

使用'/ dev/null'是正確工作的關鍵。由於某些原因,當我指定一個實際的日誌文件位置(即@zaf建議的'/ path/to/logfile')時,PHP仍然等待該過程完成。任何想法,爲什麼這是? –

1

這裏是我使用(你可以使用EXEC或系統代替paasthru):

passthru("/path/to/program args >> /path/to/logfile 2>&1 &"); 
+0

謝謝!不過,我並不太熟悉這裏的一些語法。 '>>和'2>&1&'做什麼? –

+0

>>將程序的輸出發送到日誌文件。 '2>&1'會將錯誤消息重定向到標準輸出,基本上意味着所有的輸出都會轉到日誌文件。 '&'表示在後臺運行命令。 – zaf

+0

完美。謝謝! –

相關問題