简体   繁体   中英

Echo program out to file even if a kill the program (linux)

I have a C program that outputs some information to the console and then goes to infinite loop. I need to run the program on the background and redirect the output to a log file. The redirection works if the program does not have the infinite loop, what nothing is written if the program have the infinite loop.

for example, this program test.c :

#include <stdio.h>
main (void) {
printf("Hello world\n");
while(1);
}

if i run it i see on the console the line Hello world but if i run ./test > logfile i don't get anything written on the file.

Is there any way to do this to work?

Thanks!

Welcome to the world of buffered input/output.

Use either non-buffered syscalls ( open , read , write ) or flush the stream.

Edit: Also, it might be a filesystem issue. Do a sync on the file system.

The output is in an in-memory buffer within the process.

Without the infinite loop, the buffer is flushed just before the process exits, by code in the C library.

One simple way to fix it is to insert:

setlinebuf(stdout);

at the start of the program: then each line will be flushed after it's written. (See man setbuf(3) .) You can also fflush() before entering the infinite loop, but if you expect this program to trickle output out, in between computations, it's simpler just to fix the buffering once than to remember to flush every time.

C defaults to line buffering when writing to a terminal, but a larger buffer when writing to a file, which is why you don't see this without the redirection.

Try this:

#include <stdio.h>
main (void) {
printf("Hello world\n");
fflush(stdout); // <--
while(1);
}

For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function.

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