简体   繁体   中英

shell script to redirect the output

I am looking for a help regarding a shell script to redirect the output of a command to a file. I have a C program that reads the input from a serial port and display. I want this data to be redirected to a file. I am executing this from a java program by calling

Runtime r = Runtime.getRuntime();
Process procObj = r.exec("sh " + scriptfile);

I have tried writing the script file as

./program >> file.txt

The file.txt is not getting updated. Here, the program doesn't end until the connection to the port is lost, in a sense it is infinitely running. So my program keeps looking for data on the port and display as and when it is there. I just need to redirect the same output to a file that I would use as a log. I looked at How to make shell output redirect (>) write while script is still running? but not helpful.

Kindly help..

How much output does program generate? Using standard IO redirection will add a 4KB buffer between stdout and file . This means your program must output more than 4KB of data before the OS starts to write to the file.

To fix this, add stdout.flush() to your program when a "work unit" is complete (maybe a line but might be more than one line).

您可以尝试./program >> file.txt 2>>file.txt还是./program 2>&1 >>file.txt

just try this

    List<String> cmd = new ArrayList<String>();
    cmd.add("sh");
    cmd.add("-c");
    cmd.add("program 1> file.txt 2>&1");

    ProcessBuilder pb = new ProcessBuilder(cmd);
    Process p = pb.start();

If you use standard C calls for output ( printf , puts etc.), your output may get buffered. On C89 and onwards, it depends on the buffering mode (unbuffered, fully buffered, line buffered) and on the size of the buffer, whether your output is buffered at all and when the buffer is flushed (see http://www.gnu.org/software/libc/manual/html_node/Buffering-Concepts.html and man setvbuf ).

By default, output to a file is fully buffered on Linux. If you want the output to appear immediately in the output file, you may:

This behaviour is not related on the fact the you start your C program in a Java program via a shell script. This behaviour depends on the standard C library that you have linked into your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM