Why would I use "service sshd reload" in preference to "service sshd restart"?

Tim Bellis picture Tim Bellis · Jul 11, 2013 · Viewed 29.2k times · Source

From my tests on Linux, it seems like

service sshd reload

  • Only works when sshd is already running
  • Stops sshd if the sshd_config file has problems
  • Returns error code 0 even if the sshd_config file has problems

service sshd restart

  • Works regardless of whether sshd is already running
  • Stops sshd if the sshd_config file has invalid syntax or other problems
  • Returns non-zero error code if the sshd_config file has problems

I understand that they are performing different operations, but it seems to me a no brainer that I should always use service sshd restart. Are there any reasons why service sshd reload is preferable in some situations?

Answer

nay743 picture nay743 · Aug 30, 2013

When you run the service sshd command where opt could be reload/restart it actually runs a program with a modified enviroment just like this:

    env -i PATH="$PATH" TERM="$TERM" "${SERVICEDIR}/${SERVICE}" ${OPTIONS}

e.g.:

    env -i PATH=/sbin:/usr/sbin:/bin:/usr/bin TERM=xterm /etc/init.d/sshd reload

The sshd command does almost the same thing in both cases (restart/reload):

reload: Tries to kill the process sending a HUP signal, and as you can see on the snipet it needs the PID of the process to do it. (Works regardless of whether sshd is already running)

    reload()
    {
        echo -n $"Reloading $prog: "
        if [ -n "`pidfileofproc $SSHD`" ] ; then
             killproc $SSHD -HUP
        else
             failure $"Reloading $prog"
        fi
        RETVAL=$?
        echo
    }

restart: It would just do the same as if you were to execute a stop->start.

    restart() {
        stop
        start
    }

    start()
    {
         [ -x $SSHD ] || exit 5
         [ -f /etc/ssh/sshd_config ] || exit 6
         # Create keys if necessary
         if [ "x${AUTOCREATE_SERVER_KEYS}" != xNO ]; then
              do_rsa1_keygen
              do_rsa_keygen
              do_dsa_keygen
         fi

         echo -n $"Starting $prog: "
         $SSHD $OPTIONS && success || failure
         RETVAL=$?
         [ $RETVAL -eq 0 ] && touch $lockfile
         echo
         return $RETVAL
    }

    stop()
    {
         echo -n $"Stopping $prog: "
         if [ -n "`pidfileofproc $SSHD`" ] ; then
             killproc $SSHD
         else
         failure $"Stopping $prog"
         fi
         RETVAL=$?
         # if we are in halt or reboot runlevel kill all running sessions
         # so the TCP connections are closed cleanly
         if [ "x$runlevel" = x0 -o "x$runlevel" = x6 ] ; then
             trap '' TERM
             killall $prog 2>/dev/null
             trap TERM
         fi
         [ $RETVAL -eq 0 ] && rm -f $lockfile
         echo
    }