重定向标准输出stderr到syslog

重定向标准输出stderr到syslog

问题描述:

在程序中,我希望将所有printfs写入syslog.我将所有printf替换为syslog,所以我想到了将stdout和stderr重定向到syslog.为此,我尝试了以下代码

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);
}

问题是stderr转到syslog,屏幕上没有任何打印内容,程序已挂起. 请提出建议.

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

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

这应该解决它.

fflush()将强制从stdout写入缓冲的数据.

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