Ohhh
Ohhh

Reputation: 435

Nodejs Terminate Spawned Child Process

I started a child process for a jar file by

var exec = require('child_process').exec;
// Start child process
var child = exec("java -jar test.jar");

and I terminated the child process by using a kill function that I wrote given the pid of the child

killProcess(child.pid);

The function always work when the pid is correct, however, because nodejs created the child process inside a cmd.exe shown in the picture below, and the child.pid is the pid for the cmd.exe not the actual java.exe

enter image description here

My problem is that, occasionally, the java.exe will get too large and jump out of the cmd.exe and become an independent process, and I can't terminate it even when I stop the server. And because I don't have the pid of the java.exe I can't terminate it with my function.

What other ways can I terminate the process without doing it manually, or get the pid of the java.exe and not the cmd.exe?

Upvotes: 1

Views: 718

Answers (1)

Ohhh
Ohhh

Reputation: 435

It turns out, the problem is with the way how I create the child process.

Creating child process with exec has a size limit, thus, change it from exec to spawn solves the problem.

// Spawn the external jar file as a child process and listen print the output
var spawn = require('child_process').spawn;
// Start child process
var child = spawn('java', ['-jar', file_name]);

Upvotes: 1

Related Questions