clinuxforkdup2

realtime redirecting stdout to file in linux c


I am trying to implement following bash line in c.

while true; do echo Hello; done > out.log

I can collect log in log file .

But logs are written only when executable finishes execution.

my test case which uses non exiting executable fails.

how do I write log file realtime ?

here is hello.c

#include <stdio.h>
#include <unistd.h>

int main(){
//      while(1){
        for(int i=0; i<10;i++){
                printf("Hello World\n");
                sleep(1);
        }
        return 0;
}

here is helloExec.c

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(){
        char *cmd[] = {"./hello", NULL};
        int fd = -1;
        if(fork() == 0){
                fd=open("log.out", O_RDWR | O_CREAT | O_APPEND, 0666);
                dup2(fd,1);
                execv(cmd[0],cmd);
        }
        return 0;
}

compiled with make hello and make helloExec

When I use for loop I do see logs collected after 10 sec. Whereas If while is used then logs are not written to file.

using tail -f log.out to follow log file.

Any inputs about this are welcome.

NOTE: unsuccessful trying to resolve this using pipe.


Solution

  • Piped output is buffered even aggressively than line-buffered terminal output, \n is not enough to flush it. Use fflush(stdout) after printf()