How to kill all servers running in gulp with a single bash command

I created gulpfile.js to run my servers, and its contents 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 that at least due to preprocessor crashes, the gulpfile.js daemon crashes. The python manage.py runserver child processes python manage.py runserver python -m SimpleHTTPServer aptly api serve will still work.

I had to stop them thoroughly using ps -aux | grep runserver ps -aux | grep runserver and likewise, to find the PID to delete via sudo kill -9 $PID .

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

+5
source share
1 answer

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

 #!/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 

}

Send the file to bash with

 source ./killChilds.sh 

You can use it to destroy the entire process tree in the console with

 killChilds $pid 

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

+1
source

Source: https://habr.com/ru/post/1233489/


All Articles