简体   繁体   中英

Running jar.exe, process.waitFor never return

I have java cde that jars class files together:

    List<String> args = new ArrayList<String>();
    String path = FileSystemUtils.JavaBin() + "\\jar.exe";
    args.add(path);
    args.add("-cfv");
    args.add(jarName);
    args.addAll(FileSystemUtils.getAllFiles(directory, ".class"));
    ProcessBuilder pb = new ProcessBuilder(args);
    File wd = new File(directory);
    pb.directory(wd);
    Process p = pb.start();
    //Waiting for process to exit
    p.waitFor();
    int res = p.exitValue();

Tis code works great. However, on some computers - not on all of them, when there are 7+ files, the p.waitFor(); never return, even though the jar was created.

Looking at the task manager, jar.exe really did not terminate.... what can be the cause? running the same command manually from the command line exits immediately.

This seems very weird. Does someone have any hint?

Found the solution myself. Apparently if you use ProcessBuilder.start in Java to start an external process you have to consume its stdout/stderr, otherwise the external process hangs.

This is beacuase OS creates a pipe. All Unix like OSs and Windows behave the same in this regard: A pipe with a 4K is created between parent and child. When that pipe is full (because one side isn't reading), the writing process blocks.

It seems that when there are 7+ files the jar.exe consume 4K, nad then stuck.

Javadoc of process:

By default, the created subprocess does not have its own terminal or console. All its standard I/O (ie stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream(). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM