I'm trying to store the PID of a background process I need to launch as a non-root user.
When I execute the script below, the PID file is created but stays empty.
USER=myuser
PROG=/path/to/service
PROG_ARGS=""
PIDFILE=/var/run/$NAME.pid
su $USER -c "python2.7 $PROG $PROG_ARGS &"
echo $! > $PIDFILE
I've tried to place the &
outside the su
command like so su $USER -c "python ..." &
, and it nearly worked since I get a PID but it's always the one before my actual process (Eg: if my python PID is 3101, the saved PID will be 3100). I suspect this is the PID of the shell that launched the python script.
My question is, how can I launch my python script as a specific user and save the PID at the same time?
I'm running RHLE 6.
The background process is created in the subshell started by su
, so you need to capture $!
there.
su $USER -c "python2.7 $PROG $PROG_ARGS & echo \$! > $PID_FILE"