Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clean child processes on child_process.spawn() in node.js

The following code:

#!/usr/bin/env node
"use strict";

var child_process = require('child_process');

var x = child_process.spawn('sleep', [100],);

throw new Error("failure");

spawns a child process and exits without waiting the child process exiting.

How can I wait it? I'd like to call waitpid(2) but child_process seems to have no waitpid(2).

ADDED:

Sorry, what I really want is to kill the child process when the parent exists, instead of wait it.

like image 210
FUJI Goro Avatar asked Feb 21 '13 09:02

FUJI Goro


2 Answers

#!/usr/bin/env node
"use strict";

var child_process = require('child_process');

var x = child_process.spawn('sleep', [10]);

x.on('exit', function () {
    throw (new Error("failure"));
});

EDIT:

You can listen for the main process by adding a listener to the main process like process.on('exit', function () { x.kill() })

But throwing an error like this is a problem, you better close the process by process.exit()

#!/usr/bin/env node
"use strict";

var child_process = require('child_process');

var x = child_process.spawn('sleep', [100]);

process.on('exit', function () {
    x.kill();
});

process.exit(1);
like image 181
pfried Avatar answered Oct 22 '22 06:10

pfried


#!/usr/bin/env node
"use strict";

var child_process = require('child_process');

var x = child_process.spawn('sleep', [10]);

process.on('exit', function() {
  if (x) {
    x.kill();
  }
});
like image 32
Floby Avatar answered Oct 22 '22 07:10

Floby