How can I drop privileges and still clean up my pid file in /var/run?

Solution 1:

Don't put the PID file in /var/run/foo.pid, put it in /var/run/foo/foo.pid and have /var/run/foo owned by user foo and group foo. That way you can delete the pid file before exiting and you don't have to raise your privilege level.

Note, however, that this is a bad security practice since allowing your unprivileged application mangle with its file will open a security hole: imagine that your application is hijacked (after all what was the point of dropping privileges if not to anticipate that the application can be attacked?) -- now, the attacker updates the pid file and puts, say, sshd's pid number there. Now, when system-wide scripts (running as root) will try to stop your application using that pid file, they will shutdown sshd instead. This is just an example, there are more ways to abuse your system. All in all, the pid file should be created before dropping privileges and cleanup of the pid files should be performed by the system-wide scripts. -- Dmitry D. Khlebnikov

An even better idea would be to switch to an init system like systemd or Upstart that doesn't require PID files to manage services.

Solution 2:

You can fork a new process before running your daemon. The parent process remains with privileged user root. The child process drops its privileges to foo user. This process does the real daemon work.

The parent process will create the PID file after forking its child and will remove it when its child terminates.

Solution 3:

Taking a peek at my Ubuntu system, I see that some installed software has created directories under /var/run owned by a non-root user like jcollie suggests.

Another option is to have the pidfile owned by the non-root user and zero the file instead of deleting it.