【问题标题】:Process run in loop not logging every time进程循环运行而不是每次都记录
【发布时间】: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


    【解决方案1】:

    除了初始化之外,我从未见过您的 printstream 对象“out”被使用过。如果你想写入文件,你应该调用 printstream 对象。

    System.out.println("ExitValue: " + exitVal);
    //now call the printstream object
    out.print("ExitValue: " + exitVal);
    //flushing will force the string to be written to the file
    out.flush();
    

    您可以在每次写入控制台并写入您创建打印流对象的文件时遵循上述代码。

    【讨论】:

    • 它在 StreamGobbler 类中使用。我应该提到的。但我确实提到它在 5 次中多次写入文件,而不是全部 5 次
    • 您确定每个进程都成功启动和停止了吗?
    • 是的。这是一个 rsync 进程,它每次都在复制文件。它将流输出到控制台,而不是文件
    • 您是否在每次打印时都刷新()打印流对象?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多