|
31 | 31 | import lombok.Setter; |
32 | 32 | import org.jspecify.annotations.Nullable; |
33 | 33 |
|
34 | | -import java.io.File; |
35 | 34 | import java.io.IOException; |
36 | 35 | import java.io.InputStream; |
| 36 | +import java.io.OutputStream; |
37 | 37 | import java.io.UncheckedIOException; |
| 38 | +import java.nio.file.Files; |
38 | 39 | import java.nio.file.Path; |
39 | 40 | import java.nio.file.Paths; |
| 41 | +import java.nio.file.StandardOpenOption; |
40 | 42 | import java.util.LinkedHashMap; |
41 | 43 | import java.util.Map; |
42 | 44 | import java.util.concurrent.TimeUnit; |
|
47 | 49 | * A client for spawning and communicating with a subprocess that implements Rewrite RPC. |
48 | 50 | */ |
49 | 51 | public class RewriteRpcProcess extends Thread { |
50 | | - private static final File DEV_NULL = new File( |
51 | | - System.getProperty("os.name").startsWith("Windows") ? "NUL" : "/dev/null"); |
52 | | - |
53 | 52 | private final String[] command; |
54 | 53 |
|
55 | 54 | @Setter |
@@ -93,17 +92,41 @@ public void run() { |
93 | 92 | if (workingDirectory != null) { |
94 | 93 | pb.directory(workingDirectory.toFile()); |
95 | 94 | } |
96 | | - if (stderrRedirect != null) { |
97 | | - pb.redirectError(ProcessBuilder.Redirect.appendTo(stderrRedirect.toFile())); |
98 | | - } else { |
99 | | - pb.redirectError(ProcessBuilder.Redirect.to(DEV_NULL)); |
100 | | - } |
| 95 | + // Don't use ProcessBuilder.redirectError() — on Windows it leaks the |
| 96 | + // parent-side file handle after process termination, preventing deletion |
| 97 | + // of the log file. Instead we drain stderr in a daemon thread. |
101 | 98 | process = pb.start(); |
| 99 | + drainStderr(process, stderrRedirect); |
102 | 100 | } catch (IOException e) { |
103 | 101 | throw new UncheckedIOException(e); |
104 | 102 | } |
105 | 103 | } |
106 | 104 |
|
| 105 | + private static void drainStderr(Process process, @Nullable Path stderrRedirect) { |
| 106 | + Thread thread = new Thread(() -> { |
| 107 | + byte[] buf = new byte[8192]; |
| 108 | + try (InputStream stderr = process.getErrorStream()) { |
| 109 | + if (stderrRedirect != null) { |
| 110 | + try (OutputStream out = Files.newOutputStream(stderrRedirect, |
| 111 | + StandardOpenOption.CREATE, StandardOpenOption.APPEND)) { |
| 112 | + int n; |
| 113 | + while ((n = stderr.read(buf)) != -1) { |
| 114 | + out.write(buf, 0, n); |
| 115 | + } |
| 116 | + } |
| 117 | + } else { |
| 118 | + //noinspection StatementWithEmptyBody |
| 119 | + while (stderr.read(buf) != -1) { |
| 120 | + // discard |
| 121 | + } |
| 122 | + } |
| 123 | + } catch (IOException ignored) { |
| 124 | + } |
| 125 | + }, "rpc-stderr-drain"); |
| 126 | + thread.setDaemon(true); |
| 127 | + thread.start(); |
| 128 | + } |
| 129 | + |
107 | 130 | public @Nullable RuntimeException getLivenessCheck() { |
108 | 131 | if (process == null) { |
109 | 132 | return null; |
|
0 commit comments