最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to clean child processes on child_process.spawn() in node.js - Stack Overflow

programmeradmin9浏览0评论

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.

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.

Share Improve this question edited Feb 21, 2013 at 10:17 FUJI Goro asked Feb 21, 2013 at 9:56 FUJI GoroFUJI Goro 88910 silver badges19 bronze badges 2
  • if you throw an error the application exits if the error is not catched. You want to wait for the child process and then exit the application? – pfried Commented Feb 21, 2013 at 10:05
  • 1 In fact, I'd like to kill the child process when the parent process exits. – FUJI Goro Commented Feb 21, 2013 at 10:12
Add a ment  | 

2 Answers 2

Reset to default 13
#!/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);
#!/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();
  }
});
发布评论

评论列表(0)

  1. 暂无评论