Skip to content

Instantly share code, notes, and snippets.

@alvalea
Created December 17, 2020 12:07
Show Gist options
  • Save alvalea/1f5bc1063364c599cc66da053a2fd529 to your computer and use it in GitHub Desktop.
Save alvalea/1f5bc1063364c599cc66da053a2fd529 to your computer and use it in GitHub Desktop.
C redirect stdout and stderr to syslog using logger command
#include <stdio.h>
#include <unistd.h>
int main()
{
// Pipe open logger command in another process (sh -c logger)
FILE *fl;
fl = popen("logger","w");
if(fl == NULL)
return 1;
// Test syslog event
fprintf(fl,"logger test new\n");//this goes to /var/log/syslog
fflush(fl);
// Get the file descriptor number of the output of logger
int nf;
nf = fileno(fl);
// Create backup copy of stdout and stderr
int stdout_copy = dup(STDOUT_FILENO);
int stderr_copy = dup(STDERR_FILENO);
// Duplicate file descriptors using the previous number
dup2(nf,STDOUT_FILENO);
dup2(nf,STDERR_FILENO);
// Disable buffering for stdout and stderr (no flush needed)
setbuf (stdout,NULL);
setbuf (stderr,NULL);
// Test stdout and stderr in syslog
fprintf(stdout,"Wriiten in stdout\n");
fprintf(stderr,"Wriiten in stderr\n");
// Restore stdout and stderr file descriptors
dup2(stdout_copy, STDOUT_FILENO);
dup2(stderr_copy, STDERR_FILENO);
close(stdout_copy);
close(stderr_copy);
// Wait for the associated logger process to terminate
pclose(fl);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment