Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
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()
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question