java一段时间后杀掉进程

发布于 2024-08-20 01:20:45 字数 350 浏览 4 评论 0原文

我的代码是这样的:

        Runtime rt = Runtime.getRuntime();
        // cmd == "cmd.exe /C java =Xms2M =Xmx16M Sth" 
        Process proc = rt.exec(cmd);

现在我想在一秒钟后终止这个进程,并将他的输出和错误放入字符串变量中。

怎么办呢?

就我而言: 我在已编译的类 Sth 中有一个不定式循环。我正在启动它,然后,一秒钟后我想杀死它。

//我先在 Win XP 上测试,然后在 Debian 上测试。

谢谢 齐姆

my code goes like this:

        Runtime rt = Runtime.getRuntime();
        // cmd == "cmd.exe /C java =Xms2M =Xmx16M Sth" 
        Process proc = rt.exec(cmd);

Now i want to kill this process after a second, and get his output and error into a string variables.

How to do that ?

In my case:
I have a infinitive loop in compiled class Sth. I'm starting it and then, after one second i want to kill it.

//I'm testing it on Win XP then Debian.

thx
Tzim

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

近箐 2024-08-27 01:20:45

这会有点棘手,因为一旦终止进程,它的输出就不再可用,所以你必须在杀死它之前获取输出。

Thread.sleep(1000); 
InputStream in = proc.getInputStream();
byte[] data = new byte[in.available()];
in.read(data);
proc.destroy();

这是假设该进程在此期间不会自行关闭。如果是这样,InputStream 将无法使用,您会希望自己一直在读取数据而不是无所事事。

您肯定希望使此异常安全 - 将调用 proc.destroy 放入finally 处理程序中,以确保子进程被终止。

It will be a little tricky because once you terminate the process, its output is no longer available, so you have to grab the output before you kill it.

Thread.sleep(1000); 
InputStream in = proc.getInputStream();
byte[] data = new byte[in.available()];
in.read(data);
proc.destroy();

This is assuming that the process doesn't close itself in the meantime. If it does, the InputStream will not be available for use, and you'll wish you had been reading the data instead of twiddling your thumbs.

You'll definitely want to make this exception-safe — put the call to proc.destroy in a finally handler to ensure that the child process gets terminated.

书间行客 2024-08-27 01:20:45
Runtime rt = Runtime.getRuntime();
// cmd == "cmd.exe /C java =Xms2M =Xmx16M Sth" 
Process proc = rt.exec(cmd);

(你的cmd中有一个拼写错误,你写了“=Xms2M”而不是“-Xms2M”,“-Xmx16M”也是如此)。

永远不要像这样调用 Runtime.exec:您必须将“cmd”拆分到一个数组中,否则您会遇到很多问题。这样做:

String[] sar = { "cmd.exe", "/C", "java", "-Xms2M", "-Xmx16M", "Sth" };
Runtime.getRuntime().exec( sar );
Runtime rt = Runtime.getRuntime();
// cmd == "cmd.exe /C java =Xms2M =Xmx16M Sth" 
Process proc = rt.exec(cmd);

(You have a typo in your cmd, you wrote "=Xms2M" instead of "-Xms2M", same for "-Xmx16M").

Never call Runtime.exec like that: you must split your 'cmd' in an array or you'll encounter lots of issues. Do it like this:

String[] sar = { "cmd.exe", "/C", "java", "-Xms2M", "-Xmx16M", "Sth" };
Runtime.getRuntime().exec( sar );
万劫不复 2024-08-27 01:20:45

您可以使用 ProcessBuilder 返回一个 Process 对象并使用它的destroy() 方法。

示例

You can use ProcessBuilder which returns a Process object and use it's destroy() method.

Example

清晨说晚安 2024-08-27 01:20:45

这也可能对您有所帮助:

private static String runCommand(boolean debug, String... script) throws IOException, InterruptedException {
    Runtime rt = Runtime.getRuntime();
    Process process = rt.exec(script);
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StreamReaderUtil.UTF8));
        Thread.sleep(1000);
        StringBuilder queryExe = new StringBuilder();
        try {
            String str;
            while(reader.ready() && (str = reader.readLine()) != null) {
                queryExe.append(str).append("\n");
            }
        } catch(IllegalThreadStateException e) {
            Thread.sleep(250);
        }
        // FIXME: Replace with a Logger
        if(debug) {
            System.out.println("Executing : " + script);
            System.out.println("Result    : " + queryExe);
        }
        return queryExe.toString();
    } finally {
        if(process != null) {
            process.destroy();
        }
        if(reader != null) {
            reader.close();
        }
    }
}

This might also help you out:

private static String runCommand(boolean debug, String... script) throws IOException, InterruptedException {
    Runtime rt = Runtime.getRuntime();
    Process process = rt.exec(script);
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StreamReaderUtil.UTF8));
        Thread.sleep(1000);
        StringBuilder queryExe = new StringBuilder();
        try {
            String str;
            while(reader.ready() && (str = reader.readLine()) != null) {
                queryExe.append(str).append("\n");
            }
        } catch(IllegalThreadStateException e) {
            Thread.sleep(250);
        }
        // FIXME: Replace with a Logger
        if(debug) {
            System.out.println("Executing : " + script);
            System.out.println("Result    : " + queryExe);
        }
        return queryExe.toString();
    } finally {
        if(process != null) {
            process.destroy();
        }
        if(reader != null) {
            reader.close();
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文