【发布时间】:2016-10-14 15:40:31
【问题描述】:
我有一个类,我可以在其中从 shell 脚本运行 rsync 命令。
除了将进程输出(流内和错误流)记录到文件之外,一切都正常工作。
我的班级中有一个循环,如果进程失败,它允许运行 5 次,并且在每次运行中,每个流/写入器/读取器都被初始化并完全关闭。
问题在于该文件在 5 次运行中仅写入一次或两次,而且输出的运行次数绝不会相同。我在处理后设置了 10 秒睡眠,以使输出更具可读性,我可以看到写入文件的唯一输出是在 20 和 30 秒之后,或者在 10 和 40 秒之后等。
进程的每个输出都写入控制台而不是文件。
我的代码如下。任何建议将不胜感激。
private static void run() throws IOException {
while (retry && NUMBER_OF_TRIES >= tries){
InputStream in = null;
PrintStream out = null;
InputStream errIn = null;
try {
// get runtime object to run cmd
Runtime RT = Runtime.getRuntime();
Process PR = RT.exec( cmd );
errIn = PR.getErrorStream();
in = PR.getInputStream();
out = new PrintStream(new FileOutputStream(new File(output), true));
System.out.println("file output initialised");
StreamGobbler inConsumer = new StreamGobbler( in, new Date() + " OUTPUT: ", out );
StreamGobbler errConsumer = new StreamGobbler( errIn, new Date() + " ERROR: ", out );
System.out.println("Starting consumer threads");
inConsumer.start();
errConsumer.start();
Thread.sleep(10000);
int exitVal = PR.waitFor();
if (exitVal > 0){
retry = true;
tries++;
} else {
retry = false;
}
System.out.println("ExitValue: " + exitVal);
// Wait for the consumer threads to complete
inConsumer.join();
errConsumer.join();
} catch ( Exception e ) {
e.printStackTrace();
System.out.println( "failed: " + e.getMessage() );
} finally {
// the StreamConsumer classes will close the other streams
if ( out != null ){
out.close();
}
if (in != null){
in.close();
}
if (errIn != null){
errIn.close();
}
}
}
}
【问题讨论】:
标签: java linux process stream rsync