英文:
process.waitFor() not returning
问题
void importDatabase() {
final Process process = Runtime.getRuntime().exec("psql -f ./test.sql postgresql://postgres:root@127.0.0.1:5432/testdb");
//Wait to get exit value
try {
if (process.waitFor() != 0) {
String line;
BufferedReader input = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = input.readLine()) != null) {
log.error(line);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
waitFor
is not returning anything, it just waits forever.
Note: My test.sql
has many queries so it will display many log entries.
Question:
-
How to solve this problem?
-
If this relates to the buffer memory, how do I clear the buffer?
Thank you.
英文:
I would like to migrate data from a Postgres SQL script.
I am using the code below.
void importDatabase() {
final Process process = Runtime.getRuntime().exec("psql -f ./test.sql postgresql://postgres:root@127.0.0.1:5432/testdb");
//Wait to get exit value
try {
if (process.waitFor() != 0) {
String line;
BufferedReader input = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = input.readLine()) != null) {
log.error(line);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
waitFor
is not returning anything, it just waits forever.
Note: My test.sql
has many queries so it will display many log entries.
Question:
-
How to solve this problem?
-
If this relates to the buffer memory, how do I clear the buffer?
Thank you.
答案1
得分: 3
如果由Runtime.exec()
执行的进程产生输出,无论是对于stdout
还是stderr
,为了使其稳健地运行,您需要在调用Process.waitFor()
之前开始消耗输出。很可能,您的psql
进程被阻塞,因为它正在等待有人读取其输出,而直到Process.waitFor()
完成之前,您不会开始执行这个操作。
除非您确切知道期望的输出是什么,否则您可能需要在单独的线程中消耗输出。无论如何,关于您调用psql
的问题可能存在,除非您捕获其输出,否则您可能无法了解。
稳健且可移植地使用Runtime.exec()
是相当困难的。我在这里详细介绍了这个问题,并附有代码示例:
http://kevinboone.me/exec.html
英文:
If a process executed by Runtime.exec()
produces output -- either to stdout
or stderr
-- then for it to operate robustly you need to start consuming the output before calling Process.waitFor()
. Most likely, your psql
process is blocked because it's waiting for something to read its output, and you don't start to do that until Process.waitFor()
is complete.
You probably need to consume the output in a separate thread, unless you know exactly what output is expected. In any case, there may, or may not, be a problem with your invocation of psql
-- unless you capture its output you probably won't know.
Robust and portable use of Runtime.exec()
is surprisingly difficult. I've written about this at length, with code samples, here:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论