Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill all servers running in gulp using one bash command

I have created a gulpfile.js to start my servers, and its content can be seen below.

gulp.task('default', function () {
    if(!fs.statSync('/etc/aptly.conf').isFile()){
    process.exit();
    return;
    }

    console.info('Starting static file server SimpleHTTPServer on 0.0.0.0:8080');
    aptly_static = spawn('python', ['-m', 'SimpleHTTPServer', '8080'], {'cwd': '/opt/aptly/public', 'stdio': 'inherit'});

    console.info('Starting Django runserver on 0.0.0.0:8000');
    django = spawn('python', ['manage.py', 'runserver', '0.0.0.0:8000'], {'stdio': 'inherit'});

    console.info('Starting Aptly api serve on 0.0.0.0:4416');
    aptly_api = run('aptly api serve -listen="0.0.0.0:4416"').exec().pipe(gulp.dest('/tmp/aptlylog'));

    return watchLess('src/**/*.less')
    .pipe(debug())
        .pipe(reLess)
        .pipe(gulp.dest('dist/dist'));

The problem is if less preprocessor crashes for any reason, the gulpfile.js daemon exits poorly. The child processes python manage.py runserver python -m SimpleHTTPServer aptly api serve will still be running.

I have had to painstakingly terminate these by using a ps -aux | grep runserver and similar to find the PID to delete via sudo kill -9 $PID.

Is there a way to directly kill all the processes if my gulpfile.js crashes unexpectedly?

like image 969
python Avatar asked Oct 12 '15 00:10

python


1 Answers

Using a recurive function to send kill signal to all child processes. Create the following ./killChilds.sh file

#!/usr/bin/env bash

function KillChilds {
    local pid="${1}" # Parent pid to kill childs
    local self="${2:-false}" # Should parent be killed too ?

    if children="$(pgrep -P "$pid")"; then
        for child in $children; do
            KillChilds "$child" true
        done
    fi

    # Try to kill nicely, if not, wait 15 seconds to let Trap actions happen before killing
    if ( [ "$self" == true ] && kill -0 $pid > /dev/null 2>&1); then
        kill -s TERM "$pid"
        if [ $? != 0 ]; then
            sleep 15
            kill -9 "$pid"
            if [ $? != 0 ]; then
                return 1
            fi
        else
            return 0
        fi
    else
        return 0
    fi

}

Source the file in your bash with

source ./killChilds.sh

You can that use it to kill the whole process tree in console with

killChilds $pid

Where $pid is the main process. You might wanna include the file to ~/.bashrc so you don't have to source it every time.

like image 60
Orsiris de Jong Avatar answered Nov 10 '22 17:11

Orsiris de Jong