0
votes

I have a C program what has a "daemon" mode, so that I can have it run in the background. When it is run with "-d" it forks using the following code:

if(daemon_mode == 1)
{
    int i = fork();
    if(i<0) exit(1); // error
    if(i>0) exit(0); // parent
}

I created an init script, and when i manually run the init script to start my daemon, it starts ok, however, if i run it with "stop" the daemon isn't stopped.

I imagine the issue is that the PID has changed due to forking, what am I don't wrong and how do I fix it?

1
fork returns a pid_t, not an int. - William Pursell
Thanks for the heads up. Is that pid_t of use to solving my problem? - Hamid
No, using pid_t will have almost no bearing on anything! - William Pursell
You should call daemon(3), not just once fork(2), in daemon mode. - Basile Starynkevitch
Thanks for the tip, I'll look into daemon(3). - Hamid

1 Answers

1
votes

If you are using a pid file to control the process, then you are likely correct that changing the pid is causing a problem. Just write the pid file after you have daemonized rather than before.