Search code examples
clockingdaemon

C daemon - Release and delete a lockfile


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?


Solution

  • The lock itself is automatically released:

    reference: File locks are released as soon as the process holding the locks closes some file descriptor for the file.

    To remove the file you can use unlink. I suspect that the lock file is kept around since future invocations of the program will re-recreate it, thus reducing overhead.