Java Process destroy方法kill进程,返回码测试

时间:2022-04-27
本文章向大家介绍Java Process destroy方法kill进程,返回码测试,主要内容包括Java代码:、测试shell脚本:、总结、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

Java代码:

package com.spiro;

import java.io.IOException;

public class Main {

    public static void main(String[] args) {
	    String command = args[0];

        System.out.println("Running command [" + command + "]");

        try {
            final Process process = Runtime.getRuntime().exec(command);

            Thread t1 = new Thread() {
                @Override
                public void run() {
                    try {
                        int exitCode = process.waitFor();
                        System.out.println("Process exit with code [" + exitCode + "]");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };

            Thread t2 = new Thread() {
                @Override
                public void run() {
                    System.out.println("Waiting 2 seconds.");
                    try {
                        Thread.sleep(2000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    process.destroy();
                    System.out.println("Process destroyed");
                }
            };

            t1.start();
            t2.start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

测试shell脚本:

#!/bin/sh

echo "abc--1"
sleep 3s
echo "abc--2"
sleep 3s
echo "abc--3"

执行:

java com.spiro.Main "sh /tmp/test.sh"

结果:

Running command [sh /tmp/test.sh] Waiting 2 seconds. Process destroyed Process exit with code [143]

总结

通过 destroy 方法可以kill进程,并可以得到非0得返回码