Skip to content

Commit

Permalink
handle exiting of child process properly
Browse files Browse the repository at this point in the history
  • Loading branch information
0x7d8 committed Aug 16, 2024
1 parent a047b94 commit e81959e
Showing 1 changed file with 21 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public void startServer(String[] cmd) throws ServerStartupException {
processHolder.stdoutReader = new BufferedReader(new InputStreamReader(processHolder.process.getInputStream()));
processHolder.stderrReader = new BufferedReader(new InputStreamReader(processHolder.process.getErrorStream()));

new Thread(() -> {
Thread stdoutThread = new Thread(() -> {
try {
String line;
while ((line = processHolder.stdoutReader.readLine()) != null) {
Expand All @@ -33,9 +33,10 @@ public void startServer(String[] cmd) throws ServerStartupException {
} catch (IOException e) {
e.printStackTrace();
}
}).start();
});
stdoutThread.start();

new Thread(() -> {
Thread stderrThread = new Thread(() -> {
try {
String line;
while ((line = processHolder.stderrReader.readLine()) != null) {
Expand All @@ -44,9 +45,10 @@ public void startServer(String[] cmd) throws ServerStartupException {
} catch (IOException e) {
e.printStackTrace();
}
}).start();
});
stderrThread.start();

new Thread(() -> {
Thread stdinThread = new Thread(() -> {
try (BufferedReader userInputReader = new BufferedReader(new InputStreamReader(System.in))) {
String userInput;
while ((userInput = userInputReader.readLine()) != null) {
Expand All @@ -56,7 +58,8 @@ public void startServer(String[] cmd) throws ServerStartupException {
} catch (IOException e) {
e.printStackTrace();
}
}).start();
});
stdinThread.start();

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
if (processHolder.process != null && processHolder.process.isAlive()) {
Expand All @@ -66,18 +69,23 @@ public void startServer(String[] cmd) throws ServerStartupException {

processHolder.process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
} finally {
processHolder.process.destroy();
}
}
}));

try {
processHolder.process.waitFor();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} catch (IOException exception) {
throw new ServerStartupException("Failed to start the NeoForge server.", exception);
int exitCode = processHolder.process.waitFor();

stdoutThread.join();
stderrThread.join();
stdinThread.interrupt();

System.exit(exitCode);
} catch (IOException | InterruptedException exception) {
throw new ServerStartupException("Failed to start or monitor the NeoForge server.", exception);
} finally {
if (processHolder.process != null && processHolder.process.isAlive()) {
try {
Expand Down

0 comments on commit e81959e

Please sign in to comment.