Why am I getting a "failed to create pid file...Permission Denied" error?
If a program requires write permission how should I set it with chown? Specifically, what would program foo's permissions be to solve this error?
failed to create pid file '/var/run/bar.pid': Permission denied
Solution 1:
If you have a program foo
trying to create/write to a file, the permissions of the foo
binary don't matter, but the user it's running as makes all the difference.
In this case, foo
is trying to write to /var/run
, which is owned by root
and only writable by root.
So you would have to run the program as sudo foo
for it to create that PID file. Please consider the security implications of allowing a program to run as root before you do it...
Solution 2:
What I did is simply add the creation of a folder just before the start-stop-deamon is executed. This works because the script is generally executed as root during start up. It just creates the folder in /var/run and changes the owner immediately, so a PID can be written.
In the example below, I check for the existence of the subfolder of /var/run where i put the PIDs as the current run user, in this case user 'pi' (since I am on a raspberry).
Also check this link since it was very educational to me: Python script to run as service, however, it did not cover the problem discussed here.
Example portion of my shell script:
# The process ID of the script when it runs is stored here:
PIDFILE=/var/run/power/$DAEMON_NAME.pid
do_start () {
log_daemon_msg "Starting system $DAEMON_NAME daemon"
if [ ! -d /var/run/power ]; then
mkdir /var/run/power/
chown pi:pi /var/run/power/
fi
start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --chdir $DIR --startas $DAEMON -- $DAEMON_OPTS
log_end_msg $?
}
Solution 3:
General approach: determine the user and group of the process trying to access the file. This is often found in the configuration of the software (such as webservers/mailservers/...), but if the software is already running use this:
ps aux
Look for the process you want to configure access rights for. The first column tells you under which username it's running.
groups <username>
This will tell you to which groups the user belongs.
Change the owner or group of the file to match the service.
Note 1: As the question points out that the file is in /var/run/ I'm assuming only one process needs access, if this is not true, you shouldn't change owner or group, but you might consider adding the process' user to the group or creating a new group for this file/folder.
Note 2: Funny things can happen with apparmor, which is a security system: it can prevent processes from writing to files and folders to which they have (on filesystem level) all necessary rights. With aa-status
you can see whether a specific rule for your service is active.