Search code examples
cerror-handlingdaemonsyslogerrno

Is it possible to send the message produced by perror() to /var/log/syslog?


I'm using perror() to print error messages, like:

pid = fork();
if (pid < 0) {
    perror("couldn't fork");
    exit(EXIT_FAILURE);
}

Is it possible to use errno/perror() facilities but direct the produced messages to the system log (/var/log/syslog)?

I ask this in the context of a program which can be run in both daemon and non-daemon modes. In daemon mode, perror() messages won't appear on syslog.


Solution

  • Use strerror to get the error message based on an error code, without printing it. Then pass it to syslog like any other log message:

    syslog(LOG_ERR, "Couldn't fork: %s", strerror(errno));