Matthias Ronge
Matthias Ronge

Reputation: 10112

Bash script runs into infinite loop. Why?

This init script shall start a service using nohup with the "start" parameter. All other parameters shall be passed as-is. (Restart is provided for convenience.)

#!/bin/sh
# Foo Startup Script

LOGFILE="/var/log/foo/foo.log"
WORKDIR="/usr/local/foo"

nohup() {
        nohup $WORKDIR/bin/foo $@ >> $LOGFILE  2>&1 &
}
other() {
        $WORKDIR/bin/foo $@
}

case "$1" in
  start)
        nohup $@
        ;;
  restart)
        other stop
        nohup start
        ;;
  *)
        other $@
        exit
esac

With "start", the script runs into an infinite loop with nohup forking more and more processes (aka. fork bomb) but why? (No output is written to the log file.)

Upvotes: 0

Views: 531

Answers (2)

David Z
David Z

Reputation: 131590

Most likely:

nohup() {
        nohup $WORKDIR/bin/foo $@ >> $LOGFILE  2>&1 &
}

Your function nohup calls itself. The easiest solution is to give the function a different name.

If you want to be fancy, you could try either precomputing the full path to the nohup binary, or using the shell builtin version (if it exists):

builtin nohup --help || native_nohup="$(which nohup)"
nohup() {
        if test -z "$native_nohup"; then
                builtin nohup $WORKDIR/bin/foo $@ >> $LOGFILE  2>&1 &
        else
                $native_nohup $WORKDIR/bin/foo $@ >> $LOGFILE  2>&1 &
        fi
}

but I don't really see that being necessary or useful. It's much easier to just rename the function.

Upvotes: 1

Barmar
Barmar

Reputation: 781004

nohup() {
    /usr/bin/nohup $WORKDIR/bin/foo "$@" >> $LOGFILE  2>&1 &
}

Upvotes: 1

Related Questions