3

I know this could be easy, but I am unable to figure out. We want to run two instances of luigi on one machine so need to modify init.d script to write PID to file rather than just touching empty file.

echo -n $"Starting luigid scheduler as $LUIGID_USER: "
( ( /usr/bin/sudo -u $LUIGID_USER $LUIGID_BIN >>/var/log/luigid/server.log 2>&1 ) &)
RETVAL=$?
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/luigid && echo_success || echo_failure
echo
return $RETVAL

At present its just touching the empty PID file. I want it to write PID into the file. Also while stopping I want to kill by PID stored in PID file

echo -n $"Stopping luigid scheduler: "
killproc luigid
RETVAL=$?
[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/luigid && echo_success || echo_failure
echo

Any help please ?

Thanks

roy
  • 6,344
  • 24
  • 92
  • 174
  • 1
    If the process is critical that only one process be run at one, consider using a `lockdir` instead of a `lockfile`. See: [**How can I ensure that only one instance of a script is running at a time (mutual exclusion)?**](http://mywiki.wooledge.org/BashFAQ/045) – David C. Rankin Nov 24 '14 at 17:05

2 Answers2

8

You can get the PID of the previous command with $!

Change the start script to:

echo -n "Starting luigid scheduler as $LUIGID_USER: "
/usr/bin/sudo -u $LUIGID_USER $LUIGID_BIN >>/var/log/luigid/server.log 2>&1 &
RETVAL=$?
PID=$!
[ $RETVAL -eq 0 ] && echo $PID > /var/lock/subsys/luigid && echo_success || echo_failure
echo
return $RETVAL

Note you need to remove the brackets from around the command as they start the program in a subshell. The subshell will not return the PID of the started program back to your shell, so you should call it directly from your shell.

arco444
  • 22,002
  • 12
  • 63
  • 67
  • this didn't work for me. I was expecting PID number in /var/lock/subsys/luigi, but it was not. – roy Nov 26 '14 at 15:29
  • It doesn't echo PID of previous command. I tried this also ( ( /usr/bin/luigid --logdir=/srv/log/luigid --state-path=/srv/log/luigid/state.pickl ) & ) && echo $! – roy Nov 26 '14 at 16:06
  • Like I said, this **won't** work with the brackets. Find it hard to believe you don't see _anything_. What if you just `echo $!` directly after the command? – arco444 Nov 26 '14 at 16:22
0

(man) shlock should do the trick for that I do believe :

shlock [-du] [-p PID] -f lockfile

...

shlock uses the link(2) system call to make the final target lock file, which
is an atomic operation (i.e. "dot locking", so named for this mechanisms 
original use for locking system mailboxes).  It puts the process ID ("PID") 
from the command line into the requested lock file.

Or depending on the situation (man) flock, for a great example check this out : http://codehackit.blogspot.fr/2013/04/locking-processes-with-flock.html

masseyb
  • 3,745
  • 1
  • 17
  • 29