0

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!

3 Answers3

2

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.

Mihai Maruseac
  • 20,967
  • 7
  • 57
  • 109
1

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.

poolie
  • 9,289
  • 1
  • 47
  • 74
  • Thanks for the explanation. Non I understand the problem. It worked. – Jesus Vasquez May 08 '13 at 09:05
  • I believe that calling `fflush` is more appropriate here. – Basile Starynkevitch May 08 '13 at 10:42
  • @BasileStarynkevitch and is there any reason for that belief? – poolie May 09 '13 at 01:05
  • changing the buffering will slightly decrease performance. Calling a few times `fflush` won't, all is always helpful. – Basile Starynkevitch May 09 '13 at 06:16
  • I doubt you would be able to measure any difference in performance, except in contrived cases where the program writes a vast number of messages and does little other work. Micro-optimizations that might lose log data (if you forget to flush) and that have no demonstrable benefit are not helpful at all. If you're producing megabytes per second of log output you might have a problem, but that is not typical. – poolie May 09 '13 at 08:23
0

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.

ymn
  • 2,175
  • 2
  • 21
  • 39