How to use the pidfile library correctly? How to use the pidfile library correctly? unix unix

How to use the pidfile library correctly?


The problem is that you want to give an error message before the daemon is spawned, and that you know the PID file after the daemon is spawned.

So you typically do the pidfile_open before the fork, which gives you a possibility to give an error message. After you forked, you know the pidfile and you can do pidfile_write.


You do the pidfile_open(3) before you go into background, so you can immediately report any problems. You don't write PID just yet, because your PID will change after daemon(3). pidfile_open(3) only locks the pidfile. After daemon(3) you can call pidfile_write(3) as you now have your final PID (daemon(3) forks internally). In the main process you cannot call pidfile_close(3), because this is the whole idea - by keeping the pidfile open and locked you let others know that you are still alive. The second fork is totally optional. It illustrates common behaviour that daemons spawn child/worker processes. If you don't use them you don't need this fork(). This fork() is there only to show that in such worker process you should close the pidfile, so it is only kept open and locked by the main process and not by the child.