| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
package com.carrotsearch.procfork; |
| 8 |
|
| 9 |
import java.io.Closeable; |
| 10 |
import java.io.IOException; |
| 11 |
import java.io.InputStream; |
| 12 |
import java.nio.file.Files; |
| 13 |
import java.nio.file.Path; |
| 14 |
import java.time.Instant; |
| 15 |
import java.util.ArrayList; |
| 16 |
import java.util.List; |
| 17 |
import java.util.concurrent.ExecutionException; |
| 18 |
import java.util.stream.Collectors; |
| 19 |
|
| 20 |
public class ForkedProcess implements Closeable { |
| 21 |
private final Process p; |
| 22 |
private final Path processOutput; |
| 23 |
|
| 24 |
public ForkedProcess(Process p, Path processOutput) { |
| 25 |
this.p = p; |
| 26 |
this.processOutput = processOutput; |
| 27 |
} |
| 28 |
|
| 29 |
public Process getProcess() { |
| 30 |
return p; |
| 31 |
} |
| 32 |
|
| 33 |
public List<ProcessHandle> destroyForcibly() { |
| 34 |
ArrayList<ProcessHandle> procList = getProcessHandles(); |
| 35 |
|
| 36 |
for (ProcessHandle ph : procList) { |
| 37 |
if (ph.isAlive()) { |
| 38 |
ph.destroyForcibly(); |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
return procList; |
| 43 |
} |
| 44 |
|
| 45 |
public Path getProcessOutputFile() { |
| 46 |
return processOutput; |
| 47 |
} |
| 48 |
|
| 49 |
public InputStream getProcessOutputAsStream() throws IOException { |
| 50 |
return new TailInputStream(processOutput, () -> !p.isAlive()); |
| 51 |
} |
| 52 |
|
| 53 |
public int waitFor() throws InterruptedException { |
| 54 |
return getProcess().waitFor(); |
| 55 |
} |
| 56 |
|
| 57 |
@Override |
| 58 |
public void close() throws IOException { |
| 59 |
List<ProcessHandle> handles = destroyForcibly(); |
| 60 |
|
| 61 |
try { |
| 62 |
for (ProcessHandle handle : handles) { |
| 63 |
handle.onExit().get(); |
| 64 |
} |
| 65 |
} catch (ExecutionException | InterruptedException e) { |
| 66 |
throw new IOException(e); |
| 67 |
} |
| 68 |
|
| 69 |
Instant deadline = Instant.now().plusSeconds(2); |
| 70 |
try { |
| 71 |
while (true) { |
| 72 |
try { |
| 73 |
Files.deleteIfExists(processOutput); |
| 74 |
break; |
| 75 |
} catch (IOException e) { |
| 76 |
if (Instant.now().isAfter(deadline)) { |
| 77 |
throw e; |
| 78 |
} else { |
| 79 |
|
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
|
| 84 |
Thread.sleep(250); |
| 85 |
} |
| 86 |
} catch (InterruptedException e) { |
| 87 |
throw new IOException(e); |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
private ArrayList<ProcessHandle> getProcessHandles() { |
| 92 |
ArrayList<ProcessHandle> procList = |
| 93 |
p.descendants().collect(Collectors.toCollection(ArrayList::new)); |
| 94 |
procList.add(p.toHandle()); |
| 95 |
return procList; |
| 96 |
} |
| 97 |
} |