Redirect stdout and stderr to syslog

In a program, I want all printfs to be written to syslog. I am replacing all printf with syslog, so I was thinking about redirecting stdout and stderr to syslog. For this I tried the following code

int main()
{
    FILE *fl;
    fl = popen("logger","w");
    if(fl == NULL)
        return 1;
    fprintf(fl,"logger test new");//this goes to /var/log/messages
    int nf;
    nf = fileno(fl);
    dup2(nf,STDOUT_FILENO);
    dup2(nf,STDERR_FILENO);
    fprintf(stdout,"Wriiten in stdout\n");
    fprintf(stderr,"Wriiten in stderr\n");
    pclose(fl);
}

      

The problem is that stderr goes to syslog and nothing is printed to the screen and the program hangs. Please suggest.

+3


source to share


2 answers


dup2(nf,STDOUT_FILENO);
dup2(nf,STDERR_FILENO);
fprintf(stdout,"Wriiten in stdout\n");
fprintf(stderr,"Wriiten in stderr\n");
fflush(stdout);

      

This should fix the problem.



fflush()

forces buffered data to be written from stdout.

+4


source


An alternative fflush(stdout)

could be to turn off stdout buffering using:



setbuf (stdout,NULL);

      

+2


source







All Articles