4

I have an init.d script to start crond which specifies the following for start():

start-stop-daemon -S --quiet --make-pidfile --pidfile /var/run/crond.pid --background --exec /usr/sbin/crond

However, the PID is always one number higher than what's recorded in /var/run/crond.pid. Does anyone have any idea what's going on here? I have approximately ten other init.d scripts that also make the same calls, and only cron.d has this issue.

EDIT: This is interesting:

# /usr/sbin/crond &
#
[1]+  Done                       /usr/sbin/crond
# echo $!
737
# ps -eaf | grep crond
738 root     /usr/sbin/crond
740 root     grep crond
#
trycatch
  • 623
  • 2
  • 8
  • 15

1 Answers1

5

The crond program is designed to be daemon. When it starts, one of the first things it does it fork a child and exit the parent. This is designed for environments where the caller is waiting for the program to exit before proceeding, whereas the daemon needs to continue executing in the background.

caller ---- fork--> wait -------------------------+-> ...
             |                                    |
             '----> exec crond ---- fork--> exit -'
                                     |
                                     '----> read crontab, wait for time of next job, ...

The PID recorded by start-stop-daemon is the PID of the parent. If no other process forks during the short interval between the two forks, the child's PID ends up being the PID of the parent plus one.

Since start-stop-daemon is designed to handle daemons and let them run in the background, tell crond to stay in the foreground, i.e. not to fork at the beginning.

caller ---- fork--> store pid; ...
             |                                    |
             '----> exec crond -f ----> read crontab, wait for time of next job, ...

With BusyBox's crond, pass it the -f option.

start-stop-daemon -S --quiet --make-pidfile --pidfile /var/run/crond.pid --background --exec /usr/sbin/crond -- -f
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
  • Of COURSE. I was just getting on this path when I found the return code was off by one even from the command line. Awesome. – trycatch Jun 03 '13 at 19:08