0

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?

Mausy5043
  • 906
  • 2
  • 17
  • 39

2 Answers2

1

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.

Kenney
  • 9,003
  • 15
  • 21
  • I would think keeping stale lock files containing an expired pid might not be desirable. – Mausy5043 Nov 07 '15 at 21:29
  • @Mausy5043 You're right, but I don't see any pid in there: it is just an empty file. – Kenney Nov 07 '15 at 21:32
  • You're right. I added the next two lines from the code to the OP to improve the context. – Mausy5043 Nov 08 '15 at 08:36
  • Yes, in that case it is much better to delete the file on exit. It will require some code changes as you can't simply `exit` anymore. – Kenney Nov 08 '15 at 15:56
  • 1
    FYI, there is an [atexit](http://man7.org/linux/man-pages/man3/atexit.3.html) function that allows you to register shutdown code. – Kenney Nov 08 '15 at 16:23
  • Thanks! I think I've got it now. Here's what I have: https://github.com/Mausy5043/myCtest/tree/master/daemon2 . – Mausy5043 Nov 08 '15 at 17:07
  • There seems to be no consensus either way. I choose to `fork` twice. Sources: https://stackoverflow.com/questions/31485204/why-fork-twice-while-daemonizing & http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ – Mausy5043 Nov 09 '15 at 16:05
  • Ah, interesting, didn't know that! – Kenney Nov 09 '15 at 16:12
0

You can unlock explicitly using F_ULOCK. By the way from fcntl manpage (which is used on linux by lockf) it is indicated that locks are removed on file close or process end.

So after dying the daemon do not hold any lock. It can so open the file and set a new lock.

hexasoft
  • 677
  • 3
  • 9