I've spawned process which sometimes take to long to run, my question is there is a way to limit this process time ? for example kill this process after 3 min ?
2 Answers
You can use process.kill
in a timeout. But remember to cancel the timeout if the child finishes before it gets fired.
Take a look at this example:
This is child.sh
that returns after 3 seconds:
#!/bin/bash
sleep 3
echo DATA FROM CHILD
This is a Node program that spawns that child:
var seconds = process.argv[2] || 2;
var spawn = require('child_process').spawn;
var child = spawn('bash', ['child.sh'], {detached: true});
var stopped;
var timeout = setTimeout(() => {
console.log('Timeout');
try {
process.kill(-child.pid, 'SIGKILL');
} catch (e) {
console.log('Cannot kill process');
}
}, seconds*1000);
child.on('error', err => console.log('Error:', err));
child.on('exit', () => { console.log('Stopped'); clearTimeout(timeout); });
child.stdout.on('data', data => console.log(data.toString()));
By default it waits for 2 seconds, which is shorter than the child needs and the child will get killed, but you can add a different number of seconds as a command line argument:
node nodeprogram.js 10
to wait for 10 seconds which is enough for the child to finish.
-
1Thanks a lot! Question: what's the difference between
process.kill(-self.child.pid, 'SIGKILL');
andself.child.kill('SIGINT');
? Commented Sep 18, 2018 at 8:14
From Node v14, spawn has a timeout value that you can specify using the options argument. From the Docs, timeout In milliseconds the maximum amount of time the process is allowed to run. Default: undefined
const spawn = require('child_process').spawn
const someProcess = spawn('yes',
['timeout in 10'],
{timeout: 5 * 1000} // 5 seconds
);
someProcess.stdout.on('data', (data) => {
console.log(data.toString())
})
someProcess.on('close', (code) => {
console.log(`Process exited with code ${code}`)
})