2

我有一个简单的 GUI 程序,其中一个功能是从文件 ping 目标。使用普通 ping xxxx 时,我的 ping 运行良好,但是当使用 -t 命令运行它时,我注意到即使关闭命令窗口 ping.exe 仍然显示在进程列表中。我知道可以使用 ctrl+c 结束该过程,但是当用户关闭 cmd 窗口时,是否有其他方法可以结束该过程?

我目前正在使用此代码:

try {
            ipPing = VNC.getIp().concat(ext);
            String command = "ping " + ipPing;
            Runtime rt = Runtime.getRuntime();
            rt.exec(command);
            rt.exec(new String[]{"cmd.exe", "/C", "\"start;" + command + "\""});

        } catch (IOException e) {
        }

任何建议和提示将不胜感激

4

1 回答 1

1

我不确定它是否有效,但您可以尝试Process.destroy()。像这样的东西:

ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "\"start;" + command + "\"");
Process p = pb.start();
//...
p.destroy();

另外,不要写空的 catch 块:

} catch (IOException e) {
}

因为如果抛出异常,将很难注意到。当然,除非您知道可以忽略该异常。

更新:

linux 操作系统的概念证明:

public static void main(String[] args) throws IOException {
    ProcessBuilder pb = new ProcessBuilder("ping","localhost");
    pb.redirectErrorStream(true);
    Process p = pb.start();
    InputStreamReader isr = new InputStreamReader(p.getInputStream());
    int ch,count = 0;
    StringBuffer sb = new StringBuffer();
    while((ch =isr.read()) > -1) {            
        sb.append((char)ch);                
       if ((char)ch == '\n') {
          System.out.println( sb.toString());
          sb = new StringBuffer();
       }
       if (count++ == 2) {
           System.out.println("destroying process");
           p.destroy();
       }
    }        
}    

输出:

destroying process
PING localhost (127.0.0.1) 56(84) bytes of data.

Exception in thread "main" java.io.IOException: Stream closed
64 bytes from localhost (127.0.0.1): icmp_req=1 ttl=64 time=0.031 ms

at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:145)
at java.io.BufferedInputStream.read(BufferedInputStream.java:308)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
at sun.nio.cs.StreamDecoder.read0(StreamDecoder.java:107)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:93)
at java.io.InputStreamReader.read(InputStreamReader.java:151)
at com.infobip.rhino.Killer.main(Killer.java:24)
Java Result: 1

因为错误流被重定向到输出流,所以这些行搞砸了

于 2013-01-16T21:01:59.297 回答