ping 的指令在windows , linux 平台上的參數不同,詳細的資訊可以google 查的到。
本程式本來的目的是要連ping 三台機器,哪台on 就用哪一台。
重點在幾段…
(一) 會用到的class - the classes you need
Runtime runtime = Runtime.getRuntime();
Process process = null;
String line = null;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
(二) ping 在linux 上的用法,以及這些class怎麼接 - ping on linux os
process = runtime.exec("ping " + ip +" -c 1 -W 1");
// -c 是 指我只ping一次,-W 是我指等一秒。不指定的話會等很久。
// -c for just ping once , -W means wait 1 second for response.
is = process.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ( (line = br.readLine()) != null) {
if(line.startsWith("64 bytes from")){
//把這個ip記下來。64 bytes from這樣的寫法不太好,因為不同的OS,在ping回傳的字樣都不同。像windows的回應方法就不同囉。
}
(三) 最重要的finally 區塊 - last but the most important thing
is.close();
isr.close();
br.close();
process.destroy();
最後一步一定要做! 不做的話他會在memory保留記憶體,就算我們這段程式結束了也一樣。
不然他不會主動close這個process,也不會去清掉memory allocation! 千萬要注意。
You must destroy this process in finally block , or the operating system will not close it for you , and you will have a serious problem of not cleaning memory allocation!
2009年4月1日星期三
訂閱:
張貼意見 (Atom)

0 意見:
張貼意見