Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[bugfix] Asynchronously read output and error streams before waitFor() #62

Merged
merged 1 commit into from
Aug 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

package com.tencent.trpc.codegen.protoc;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -111,15 +113,50 @@ private ProtocExecutionResult runProtoc(ProcessBuilder processBuilder) {
}

private ProtocExecutionResult fetchProcessResult(Process p) {
StringBuilder outputBuilder = new StringBuilder();
StringBuilder errorBuilder = new StringBuilder();

// Using threads to asynchronously read output and error streams.
Thread outputThread = new Thread(() -> {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
outputBuilder.append(line).append(System.lineSeparator());
}
} catch (IOException e) {
log.error("failed to read output stream", e);
}
});

Thread errorThread = new Thread(() -> {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(p.getErrorStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
errorBuilder.append(line).append(System.lineSeparator());
}
} catch (IOException e) {
log.error("failed to read error stream", e);
}
});

outputThread.start();
errorThread.start();

try {
int code = p.waitFor();
outputThread.join();
errorThread.join();

if (code == 0) {
return ProtocExecutionResult.success(IOUtils.toString(p.getInputStream(), StandardCharsets.UTF_8));
return ProtocExecutionResult.success(outputBuilder.toString());
} else {
return ProtocExecutionResult.fail("run protoc failed with exit-code " + code,
IOUtils.toString(p.getErrorStream(), StandardCharsets.UTF_8), null);
errorBuilder.toString(), null);
}
} catch (IOException | InterruptedException e) {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return ProtocExecutionResult.fail("execute protoc failed", null, e);
}
}
Expand Down
Loading