2011-05-29 19 views
5

我試圖做一個應用程序,它會檢查它可以ping外面,但它永遠不會停止。我怎樣才能將命令應用到終端並停止操作?實施例在以下情況下:如何使用system()或passthru()應用終端命令時停止PHP?

$ php -r "echo system('ping 127.0.0.1');" 
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data. 
64 bytes from 127.0.0.1: icmp_req=1 ttl=64 time=0.073 ms 
64 bytes from 127.0.0.1: icmp_req=2 ttl=64 time=0.073 ms 
64 bytes from 127.0.0.1: icmp_req=3 ttl=64 time=0.072 ms 
64 bytes from 127.0.0.1: icmp_req=4 ttl=64 time=0.074 ms 
64 bytes from 127.0.0.1: icmp_req=5 ttl=64 time=0.071 ms 
64 bytes from 127.0.0.1: icmp_req=6 ttl=64 time=0.073 ms 
64 bytes from 127.0.0.1: icmp_req=7 ttl=64 time=0.074 ms 
64 bytes from 127.0.0.1: icmp_req=8 ttl=64 time=0.073 ms 
64 bytes from 127.0.0.1: icmp_req=9 ttl=64 time=0.074 ms 
64 bytes from 127.0.0.1: icmp_req=10 ttl=64 time=0.081 ms 
64 bytes from 127.0.0.1: icmp_req=11 ttl=64 time=0.072 ms 
64 bytes from 127.0.0.1: icmp_req=12 ttl=64 time=0.075 ms 

注:CTRL + C施加到停止但是這將通過Web瀏覽器來執行。

回答

1

這可以用proc_open完成。舉例來說,這一計劃只會讓ping6跑了大約5秒鐘:

<?php 
$descriptorspec = array(
    1 => array("pipe", "w"), 
); 

$process = proc_open('ping6 ::1', $descriptorspec, $pipes); 

$emptyarr = array(); 
$start = microtime(true); 
if (is_resource($process)) { 
    stream_set_blocking($pipes[1], 0); 
    while (microtime(true) - $start < 5) { 
     $pipesdup = $pipes; 
     if (stream_select($pipesdup, $emptyarr, $emptyarr, 0, 100000)) 
      echo fread($pipes[1], 100); 
    } 

    fclose($pipes[1]); 
    proc_terminate($process); 
} 

在你的情況,你可能要檢查connection_aborted()。但是請注意,您必須繼續發送(和清除)用戶中止的數據才能被檢測到。

+1

謝謝,我在Zend框架中看到他們也這樣做:http://framework.zend.com/manual/en/zendx.console.process.unix.overview.html – YumYumYum 2011-05-29 18:25:09

+0

什麼是詳細的向後方法,當你可以調用具有正確標誌的子進程。 – 2011-05-29 18:56:14

+0

@Tomalak 1)這個描述了一個通用的方法,它可以用於任何子進程而不僅僅是ping; 2)您可能需要在無限期的時間內運行ping,直到用戶取消。 – Artefacto 2011-05-29 21:16:32

4

你不能。改爲將-c參數傳遞給ping

+1

謝謝,$ ping -c 2 127.0.0.1工作。但是如果無盡的時間繼續運行,這很奇怪。我們能不能得到任何命令我們觸發它的processID返回或什麼?並在睡眠後執行(4);殺(的ProcessID); ? – YumYumYum 2011-05-29 17:37:44

+0

不是'system()'和'passthru()'都不能讓PHP腳本運行,所以不會有殺死進程的機會。 – 2011-05-29 17:38:34

+1

不完全正確。它不能用'system()'或'passthru()'完成,但是'proc_open()'完全可以。 – Artefacto 2011-05-29 17:53:50

1

system()是同步的,所以你不能。確保子進程終止。

在這個例子中,ping-c 4 127.0.0.1只發送四個ping數據包。

1

正確的操作過程不是停止進程,而是提供命令行參數以使其自行終止。您正在尋找的參數是-c count只發送固定數量的請求。有關更多信息,請參閱man ping