3

In a program i want all the printfs to be written to syslog. I replace all printf to syslog so i thought of redirecting stdout and stderr to syslog. For that 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);
}

Issue is stderr goes to syslog and nothing is printed on the screen and program is hung. Please suggest.

user2008019
  • 31
  • 1
  • 2
  • Are you limited to C or would you be willing to use C++ in a solution? – Crog Jan 24 '13 at 15:48
  • You need to close `stdout` and `stderr` before the `pclose()` – Anya Shenanigans Jan 24 '13 at 16:00
  • 1
    ...reason: `stderr` works because it is unbuffered. `stdout` is buffered and closing it flushes the buffer. – William Morris Jan 24 '13 at 16:03
  • 1
    You say that "nothing is printed on the screen" as if it is a problem. Do you want your errors to be written to the stderr of the caller (the terminal if invoked from a shell) and to the system log, or only to the system log? Similarly, to you want stdout to be written twice? – William Pursell Aug 17 '14 at 13:50

2 Answers2

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

This should solve it.

fflush() will force the buffered data to be written from stdout.

askmish
  • 6,464
  • 23
  • 42
2

An alternative to fflush(stdout) could be to disable the stdout buffering using :

setbuf (stdout,NULL);
mpromonet
  • 11,326
  • 43
  • 62
  • 91