I have a daemon called foo. My init script /etc/init.d/foo starts the foo daemon and stores its pidfile in /var/run/foo.pid, which seems to be the standard place. Because /etc/init.d/foo must be run as root, it has no trouble creating and deleting pidfiles in /var/run.
The foo daemon is really the program /usr/sbin/foo which is intended to be invoked as root bu the init script but then immediately drop its privileges to the unprivileged foo user. However, I also want this /usr/sbin/foo program to delete its pidfile when it exits due to a critical error. But since it has already dropped its privileges, it no longer has the ability to delete files from the /var/run directory.
My current approach is to use seteuid instead of setuid to drop my privileges, then re-raise the privileges immediately before exiting so that I can properly delete the pidfile from /var/run. However, I've run into many, many problems with various libraries and external programs which go haywire when invoked with a different euid than uid.
Is there any other way to accomplish this? I suppose the other option is to just put my pidfile in a directory which is writable by both the root and foo users. But all of our other pidfiles are in /var/run, including pidfiles by other programs which run as unprivileged users, so I'd like to put the foo.pid file there as well.
Is there any way to do this other than using seteuid?