1
if (log_daemon) {
    pid_t pid;
    log_init();

    pid = fork();
    if (pid < 0) {
        log_error("error starting daemon: %m");
        exit(-1);
    } else if (pid)
        exit(0);

    close(0);
    open("/dev/null", O_RDWR);
    dup2(0, 1);
    dup2(0, 2);

    setsid();

    if (chdir("/") < 0) {
        log_error("failed to set working dir to /: %m");
        exit(-1);
    }
}

I have above c program, and couldnt figure out what does the exit(0); do in this case, which process does it exit? and what does the close(0); is followed for? Will the close(0); even execute?

Is this code just to test whether a child process can be created?

UPDATE: ok, I got it from this question Start a process in the background in Linux with C.

Basically, close(0); does is closes current standard input for child process and opens /dev/null as input device. This way child process will behave as a deamon and will not read anything from terminal or standard input.

Community
  • 1
  • 1

1 Answers1

4

The fork returns the process id in the parent process, and 0 in the child process. The main calling process is exiting becausepid == 0 so if (pid) is true in the parent, and false in the child. The child then proceeds to close(0), etc.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
shooper
  • 606
  • 4
  • 8
  • Thats what I thought, so parent is exiting in this case and child is taken by init, correct? –  Mar 12 '15 at 18:45