Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Kill node process on killing forever process

I have a script to start and stop my node.js server. When I stop the script, the forever process is killed however the node process is not terminated.

Is there any way to stop both forver and node process when I issue

Kill $FOREVER_PID

Here is the script -

    #!/bin/bash
path="/Users/aayush/Desktop/node/rest-api"
action="forever errorLog_express.js "

logFile="$path/system.log"
pidFile="$path/pidFile.pid"

#messages
usage="Usage : node-script.sh start|stop"
panic="Panic! nothing to do, exiting"
unknown="Unrecognized parameter"
start="[starting node-forever]"
end="[stopping node-forever]"
notRunning="Process node-forever not running"
alreadyRunning="Process node-forever already running"

if [ -z $1 ]
then
    echo $panic
    echo $usage
    exit 0;
fi

if [ $1 = "start" ]
then
    # starting process
    dummy="OK"
    if [ -f $pidFile ];
    then
        exit 0
    else
        cd $path
        echo "cd $path"
        echo $start
        echo $start >> $logFile
        $action > /dev/null 2>&1 &
        Process_Pid=$!
        echo $Process_Pid > $pidFile
        echo $dummy
        exit 0
    fi
elif [ $1 = "stop" ]
then
    # stopping process by getting pid from pid file
    dummy="OK"
    echo $end
    echo $end >> $logFile
    if [ -f $pidFile ];
    then
        while IFS=: read -r pid
        do
            # reading line in variable pid
            if [ -z $pid ]
            then
                dummy="FAILED"
                echo "Could not parse pid PANIC ! do 'ps' and check manully"
            else
                echo "Process Pid : $pid"
                kill $pid
            fi
        done <"$pidFile"
        rm $pidFile
        echo $dummy
        exit 0
    else
        echo $notRunning
        echo "FAILED"
        exit 0
    fi
else
    echo $unknown
    echo $usage
    exit 0
fi

The final script working for me -

#!/bin/bash
#proccessname: node

USER=node
PWD=node
node=node
forever=forever
path="/Users/aayush/Desktop/node/rest-api"
action="forever start -l forever.log -a -o out.log -e err.log errorLog_express.js "

start(){
cd $path
$action
     }

stop(){
  /usr/local/bin/forever stopall
 }

restart(){
stop
start
}

status(){
/usr/local/bin/forever list
}

#Options 

case "$1" in
    start)
    start
    ;;
    stop)
    stop
    ;;
    restart)
    stop
    start
    ;;
    status)
    status
    ;;
    *)
    echo $ "usage $0 {start | stop | status | restart}"

    exit 1
esac
exit 0
like image 581
Aayush Avatar asked Oct 02 '13 12:10

Aayush


1 Answers

Yes there is, use a signal handler in your script to catch the sigterm and kill the node process.

www.gnu.org/software/bash/manual/html_node/Signals.html

like image 178
DusteD Avatar answered Sep 23 '22 23:09

DusteD