【问题标题】:Why Process destroy cannot work when exec bat but not exe为什么在执行 bat 而不是 exe 时进程破坏无法工作
【发布时间】:2014-06-26 06:44:54
【问题描述】:
Process p = Runtime.getRuntime().exec(new String[] { "C:/work/bat/ConsoleApplication1.exe" });
Thread.sleep(4000);
p.destroy();
int res = p.waitFor();
System.out.println("res" + res);

这将打印res1 并且JVM 将立即停止,但如果是这样:

Process p = Runtime.getRuntime().exec(new String[] { "C:/work/bat/exe.bat" });

这也将在大约 4s 后打印res1,但 JVM 不会一次停止。 JVM 将在更多 6s 后停止。

这是exe.bat

 C:\work\bat\ConsoleApplication1.exe

这是ConsoleApplication1.exe

int _tmain(int argc, _TCHAR* argv[])
{
int a=0;
while(a<100){
    Sleep(100);
    cout<<a++ <<endl;
}
return 0;
}

那么,我怎样才能停止像exe文件这样的bat文件呢?

【问题讨论】:

    标签: java batch-file process exe destroy


    【解决方案1】:

    试试这个来终止进程。查找进程 ID 并将其与 taskkill 命令一起使用。

    Runtime rt = Runtime.getRuntime();
    rt.exec("taskkill " +<Your process id>);
    

    但它适用于 Windows。对于 Linux 使用这个 -

    rt.exec("kill -9 " +<Your process id>);
    

    【讨论】:

    • 您好,我使用“tasklist /v”查看进程列表。但是当我使用bat时,我只能看到“ConsoleApplication1.exe”而看不到“exe.bat”。那么,如何停止一个 b​​at 包含多个 exe 命令?
    • 谢谢,但我需要运行一个来自用户的 bat 文件,所以我不知道在这个 bat 中会调用哪个 exe。在我的代码中,如果超时,我将运行一个 bat 并停止它,但我发现我无法停止由 bat 调用的 exe。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多