P
P
parkito2016-05-28 14:27:11
linux
parkito, 2016-05-28 14:27:11

How to create a daemon in C?

Hello. Please help me with the following question.
I'm writing a simple demon.

int main() {
    int pid = 0, ppid = 0;
    ppid = fork(); //1
    if(ppid<0)
        exit(1);
    chdir("/"); //2
    pid = setsid();//3
    //4
    demon();
    printf("%d\n", pid);
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
    return 0;
}

And I want to display its PID. But printf("%d\n", pid) Displays for me, for some reason, 2 numbers: the PID of the parent and 1.
Two questions follow from this. Why am I getting 2 numbers even though printf("%d\n", pid) is the only one? What am I doing wrong when creating a daemon?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
1
1001001, 2016-05-28
@parkito

fork(); creates a second process with pid = 0,
Cut off the new process if (!ppid){...} else return 0;
and already set a new indicator for it, go to the root... and get its pid via getpid()

D
Denis Zagaevsky, 2016-05-28
@zagayevskiy

Because that's how fork works. At this point, the program seems to be divided into two parts - the parent continues to work and the child begins to work. You can determine where you are by the result of fork. On success, the PID of the child process is returned to the parent, and 0 is returned to the child.

#
#algooptimize #bottize, 2016-05-28
@user004

read about fork

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question