How to create daemon in C?

Hello. Please help with the following question.
Write a simple daemon.
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 want to get its PID. But printf("%d\n", pid) Outputs I, for some reason, number 2: PID of parent and 1.
Hence two questions. Why do I displays 2 numbers, although printf("%d\n", pid) one? What am I doing wrong when creating the demon?
July 9th 19 at 10:59
3 answers
July 9th 19 at 11:01
Solution
fork(); creates a second process with pid = 0,
Trim the new process if (!ppid){...} else return 0;
and already for it install a new indicator, go to the root... and get its pid using getpid()
How is it possible to cut off? If(ppid==0){continue working with deman}, then the condition is never executed. Don't know if it is the two "flow" with ppid=ppid and N=0, why ppid=0 misses is the condition? - Oceane57 commented on July 9th 19 at 11:04
if(ppid==0){continue working with deman} - how did you determine that the condition is not met? - dariana_Sauer commented on July 9th 19 at 11:07
in the body the conditions no calls - Oceane57 commented on July 9th 19 at 11:10
int main() {
int ppid = 0;
ppid = fork();
if(ppid==0){
printf("Hello\n");
}
return 0;
}
Quite everything works - dariana_Sauer commented on July 9th 19 at 11:13
July 9th 19 at 11:03
Because works fork. At this point, the software is divided into two parts - continues to work with the parent and the child. To determine where you are, is the result of fork. Upon successful completion, the parent returns the PID of the child process, and child is returned 0.
July 9th 19 at 11:05
read about fork

Find more questions by tags CC++Linux