user4602228
user4602228

Reputation:

Node JS - Cannot Kill Process Executed with Child Process Exec

We are trying to kill the process of a chrome browser launched with nodes child_process exec command

var process = cp.exec(`"chrome.exe" --app="..."`, () => {}); // working great

But when we try

process.kill(); //nothing happens...

Does the process refer to the chrome window or something else? if not, how can we get a hold of the newly opened chrome window process, PID, etc...?

Any help would be great...

Note - we have tried using the chrome_launcher NPM but it didn't help because we couldn't open chrome in kiosk mode without fullscreen, but this is an issue for a different question...

Upvotes: 10

Views: 17479

Answers (3)

craigw
craigw

Reputation: 715

I built a cross platform npm package that wraps up spawning and killing child processes from node, give it a try.

https://www.npmjs.com/package/subspawn

Upvotes: 1

Thanveer Shah
Thanveer Shah

Reputation: 3333

Try the PID hack

We can start child processes with {detached: true} option so those processes will not be attached to main process but they will go to a new group of processes.

Then using process.kill(-pid) method on main process we can kill all processes that are in the same group of a child process with the same pid group. In my case, I only have one processes in this group.

var spawn = require('child_process').spawn;

var child = spawn('your-command', {detached: true});

process.kill(-child.pid);

Upvotes: 16

Soheb M
Soheb M

Reputation: 44

I am not able to add comment, so I am saying it directly in the answer:

How to kill process with node js

If you check the link above you need library as follows

https://www.npmjs.com/package/fkill

Usage Example taken from stackoverflow question

const fkill = require('fkill');

fkill(1337).then(() => {
    console.log('Killed process');
});

fkill('Safari');

fkill([1337, 'Safari']);

I also found this library to check running processes

https://github.com/neekey/ps

Upvotes: -1

Related Questions