While daemonizing my program in C using code "stolen" from this webpage upon initialisation the daemon creates a lockfile which stores the process pid thusly:
:
lfp=open(LOCK_FILE,O_RDWR|O_CREAT,0640);
if (lfp<0) exit(1); /* can not open */
if (lockf(lfp,F_TLOCK,0)<0) exit(0); /* can not lock */
sprintf(str,"%d\n",getpid());
write(lfp,str,strlen(str)); /* store pid in file */
:
The webpage doesn't seem to bother with cleaning up after the daemon terminates. In fact, searching the web I cannot find a way to handle this.
All examples of daemonizing C-code will create a lockfile, but none remove it afterwards.
How should I unlock and then remove the pidfile assuming that I can catch SIGTERM and exit gracefully?