0

I got a sample ping program with a little modification...

    String ip = "192.168.1.1 -t";
    String pingResult = "";      
    String pingCmd = "ping " + ip;

    try{

        Runtime r = Runtime.getRuntime();
        Process p = r.exec(pingCmd);

        Pattern pattern = Pattern.compile("time=(\\d+)ms");
        Matcher m = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            m = pattern.matcher(inputLine);
            if (m.find()) {
                System.out.println(m.group(1));
            }
        }
        in.close();

    }
    catch (IOException e) {
        System.out.println(e);
    }

I going to implement a GUI which include a start and exit button, the start button works but the exit buttons won't. When I click the exit button, the program do not show the rtt time output. But the program do not actually exit-ed/ stopped. How am I totally to shut it down, am I going to add something likeRuntime.getRuntime().addShutdownHook.

Need some hints and guidelines, thanks in advanced...

薛源少
  • 306
  • 1
  • 6
  • 18

2 Answers2

0

You can use ping's -n parameter and start after n pings again or stop if user required to halt.

Process has also an OutputStream. You may try to send a Ctrl-C when you want to stop ping.

PeterMmm
  • 24,152
  • 13
  • 73
  • 111
  • thanks, for certainty. Am I going to pass something like char ctrlBreak = (char)3; into the Process p OutputStream? – 薛源少 Mar 04 '13 at 12:02
  • look here http://stackoverflow.com/questions/1835885/send-ctrl-c-to-process-open-by-java – PeterMmm Mar 04 '13 at 12:14
0
boolean isStoped=false;

while ((inputLine = in.readLine()) != null && (!isStoped)) {
            m = pattern.matcher(inputLine);
            if (m.find()) {
                System.out.println(m.group(1));
            }
        }

make isStoped=true and call p.destroy() when you click the exit button. Hope this will help you.

  • thanks a lot, but the p.destroy() only can stop the print line but not the ping program which run on the background of the Threads... Thanks for the idea... – 薛源少 Mar 24 '13 at 14:20