从java初始化批处理脚本后退出

时间:2021-06-09 23:21:43

I want to initialize one batch script using java code. Once it is initialized I need to exit the java program and wants the batch script to continue executing. How can I achieve this. I used Runtime and Process to do this. But it is waiting for the batch script to finish before proceeding to the next. This is the sample program I tried out.

我想使用java代码初始化一个批处理脚本。初始化后,我需要退出java程序并希望批处理脚本继续执行。我怎样才能做到这一点。我使用Runtime和Process来做到这一点。但它正在等待批处理脚本完成,然后继续下一步。这是我试过的示例程序。

        try {
            Runtime r = Runtime.getRuntime();
            System.out.println("Executing process");
            Process p = r.exec("c:\\anoop\\ping.bat");
            System.out.println("Executed process"); 
            p.waitFor();
            System.out.println("Exiting with out :: ");
        } catch (Exception e) {// Catch exception if any
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }

If I use p.exitValue(), it is giving error java.lang.IllegalThreadStateException: process has not exited. In short, I just want to initialize a batch script and then exit from the java program.

如果我使用p.exitValue(),它会给出错误java.lang.IllegalThreadStateException:进程尚未退出。简而言之,我只想初始化批处理脚本然后退出java程序。

Thanks, Anoop

1 个解决方案

#1


0  

To get the exit value of the process, use:

要获取进程的退出值,请使用:

int res = p.waitFor();
System.out.println("Exiting with out :: " + res);

If you want the process to just continue, don't wait for it (don't call wait())

如果您希望该过程继续,请不要等待它(不要调用wait())

If the process expects input, or produces some output, you have to handle that (preferably on separate threads) since all I/O is redirected.

如果进程需要输入或产生一些输出,则必须处理(最好在不同的线程上),因为所有I / O都被重定向。

#1


0  

To get the exit value of the process, use:

要获取进程的退出值,请使用:

int res = p.waitFor();
System.out.println("Exiting with out :: " + res);

If you want the process to just continue, don't wait for it (don't call wait())

如果您希望该过程继续,请不要等待它(不要调用wait())

If the process expects input, or produces some output, you have to handle that (preferably on separate threads) since all I/O is redirected.

如果进程需要输入或产生一些输出,则必须处理(最好在不同的线程上),因为所有I / O都被重定向。