Skip to content

Instantly share code, notes, and snippets.

@ivanalejandro0
Created October 18, 2019 14:59
Show Gist options
  • Save ivanalejandro0/881c97df5afc1fdd1e86b2caf4e2d637 to your computer and use it in GitHub Desktop.
Save ivanalejandro0/881c97df5afc1fdd1e86b2caf4e2d637 to your computer and use it in GitHub Desktop.
Spawn and kill a bash script from js. Handle signal from bash.
#!/bin/bash
trap 'handle_signal SIGINT' SIGINT
trap 'handle_signal SIGQUIT' SIGQUIT
trap 'handle_signal SIGTERM' SIGTERM
trap 'handle_signal SIGHUP' SIGHUP
trap 'handle_signal SIGKILL' SIGKILL # we can't handle this
handle_signal() {
echo "received: $1. Exiting..."
exit
}
count=0
while true; do
sleep 1
count=$(( $count + 1 ))
echo $count
done
#!/usr/bin/env node
const { spawn } = require('child_process');
const path = require('path');
const script = spawn(path.join(__dirname, 'counter.sh'));
// Log the script output
script.stdout.on('data', function(data) {
console.log(data.toString().trimEnd());
});
setTimeout(function() {
// script.kill('SIGTERM'); // works
// script.kill('SIGHUP'); // works
// script.kill('SIGKILL'); // works but script can't handle it
script.kill('SIGINT'); // works
}, 3000)
@ivanalejandro0
Copy link
Author

To run this you'll need to:

$ chmod +x counter.sh run-script.js

Example run:

$ ./run-script.js
1
2
received: SIGINT. Exiting...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment