-1

I'm trying to execute a visual basic script code in my java application using process builder. As script provided by the user might not finish its execution in time, I want to provide means to limit this execution time. In the following code, you can see my logic but it doesn't really do what it supposed to do. How can I make this waitfor work in order to limit the execution time?

private void run(String scriptFilePath) throws ScriptPluginException {
BufferedReader input = null;
BufferedReader error = null;

try {

    ProcessBuilder p = new ProcessBuilder("cscript.exe", "//U", "\"" + scriptFilePath + "\"");

    String path = "";

    if (scriptFilePath.indexOf("/") != -1) {
        path = scriptFilePath.substring(0, scriptFilePath.lastIndexOf("/"));
    }

    path += "/" + "tempvbsoutput.txt";
    p.redirectOutput(new File(path));
    Process pp = p.start();

    try {
        pp.waitFor(executionTimeout, TimeUnit.MINUTES);     
    } catch (InterruptedException e) {
        SystemLog.writeError(jobId, ScriptConsts.COMPONENT_ID, "VBScriptExecutor", "run", 80401104,
                "VB Script executes fail.");
    } 

    if (!pp.isAlive()) {
        pp.getOutputStream().close();
    }

    // rest of the code flow 

}

Ahmet Eroğlu
  • 594
  • 1
  • 7
  • 23
  • 1
    "but it doesn't really do what it supposed to do" What do you think it's supposed to do, and what does it do instead? – Andy Turner Jan 17 '20 at 12:40
  • When the script execution takes more than the time specified in the waitfor method, its execution should be terminated. I don't see any reason why it is not clear with the writing above. – Ahmet Eroğlu Jan 17 '20 at 12:42
  • 4
    [The Javadoc of `waitFor`](https://docs.oracle.com/javase/8/docs/api/java/lang/Process.html#waitFor-long-java.util.concurrent.TimeUnit-) says "Causes the current thread to wait, if necessary, until the subprocess represented by this Process object has terminated, **or the specified waiting time elapses**." (emphasis added). It doesn't say the process is terminated if the time elapses. – Andy Turner Jan 17 '20 at 12:44

1 Answers1

5

Process.waitFor(long, TimeUnit) waits until the process has terminated or the specified time elapsed (Javadoc). The return value indicates whether the process exited or not.

if (process.waitFor(1, TimeUnit.MINUTES)) {
    System.out.println("process exited");
} else {
    System.out.println("process is still running");
}

waitFor() does not kill the process after the time elapsed.

If you want to kill the subprocess, use either destroy() or destroyForcibly().

thokuest
  • 5,800
  • 24
  • 36