user1295872
user1295872

Reputation: 509

I am trying to log a daemon's output to a file

The code I have is as follows. I am creating a daemon process. Before that I am closing the standard out, std in and std err. And duping the descriptors to the file descriptor I have opened. The signal code is extraneous to the question.

 #include<stdio.h>
#include<signal.h>
#include<unistd.h>
#include <fcntl.h>
#include<errno.h>
void signal_handler(int);
void main(){

int null_fd = -1;
int out_fd = -1;
int i=1;



if((null_fd = open("/dev/null", O_WRONLY)) == -1) {
    printf("Can't open /dev/null: %s\n", strerror (errno));
    exit(1);
}

if ((out_fd = open("sup.console", O_CREAT | O_WRONLY | O_APPEND, 0666)) == -1) {
    printf(" Can't open \"%s\" for stdout: %s\n", "sup.console", strerror(errno));
    exit(1);
}

close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);

dup2(null_fd, STDIN_FILENO);
dup2(out_fd, STDOUT_FILENO);
dup2(out_fd, STDERR_FILENO);

    This is where I create a daemon

    if(daemon(0,0)!=0){
            printf("Couldnt become a daemon\n");
            exit(1);
    }

    if(signal(SIGUSR1,signal_handler)==SIG_ERR){
            printf("Not able to register signal");
            exit(1);
        while(i<10){
            printf("From the daemon\n");
    }
}
void signal_handler(int signum){
    if(signum==SIGUSR1){
            printf("signal caught\n");
            exit(0);
    }
 }

Upvotes: 0

Views: 316

Answers (1)

Chris J. Kiick
Chris J. Kiick

Reputation: 1505

What exactly is your question?

From the daemon() man page:

If noclose [2nd argument] is zero, daemon() redirects standard input, standard output and standard error to /dev/null; otherwise, no changes are made to these file descriptors.

So if you set up your file descriptors before you call daemon(), they are going to get trashed unless you put a non-zero value in the second argument.

You might also want to check the return values from dup2 to make sure you got the fd you wanted.

Upvotes: 1

Related Questions