2016-09-02 37 views
0

我有一個bash腳本類似於以下PHP在bash腳本調用了shell_exec運行的後臺進程超時

echo "Do something" 
/bin/sh -c 'echo $$>pidfile && exec "command"' & 
echo "Ran Command">/path/to/outputfile.txt 
exit 0 

幾行然後我調用PHP腳本中
return shell_exec("/path/to/bash/script arguments");

現在,當我這樣做時,命令運行成功,outputfile.txt包含「Ran命令」。

然而,PHP腳本超時10ish秒後。 的bash腳本大約需要2-3秒運行

如果我改變行 return shell_exec("/path/to/bash/script arguments >/dev/null 2>&1");

然後執行和PHP腳本不會超時。

我明白爲什麼重定向輸出可以讓PHP繼續執行,但我不明白,爲什麼PHP是擺在首位超時要求我這樣做。有人可以給我一些幫助嗎?

+0

的'斌/ sh'應該使用'2>&1&'instaed的'&'而已,因爲你正在將腳本移動到背景中,但輸出仍然在管理着bash腳本。也許PHP等待vor stdin/stderr關閉。 – JustOnUnderMillions

+0

如果是這樣的話,如果我手動運行'/ path/to/bash/script arguments',不應該發生相同的超時(或明顯掛起)嗎?它沒有。只有當我通過php的shell_exec()來運行時纔會發生。 – Trel

+0

'>的/ dev/null的2>&1&'看這裏http://unix.stackexchange.com/questions/70963/difference-between-2-2-dev-null-dev-null-and-dev-null- 21#70971 – JustOnUnderMillions

回答

2

測試這兩個版本,你會得到它:

test1.sh /bin/sh -c 'sleep 10' >/dev/null 2>&1 &

test2.sh /bin/sh -c 'sleep 10' &

運行都與PHP命令行像

test1.php <?php shell_exec('test1.sh');

test2.php <?php shell_exec('test2.sh');

並查看區別。

test2.sh正在10ish秒test1.sh工作就像你

return shell_exec("/path/to/bash/script arguments >/dev/null 2>&1");

+0

它確實有效,我會將其標記爲解決方案(我將把'>/dev/null 2>&1'部分放在bash腳本中),但我仍然有點茫然。在PHP下運行它們的行爲有所不同。然而,在bash中,'。/ test1.sh'和'。/ test2.sh'執行完全一樣, – Trel