1 | /**
|
2 | * @module spawn-posix
|
3 | * @author Toru Nagashima
|
4 | * @copyright 2015 Toru Nagashima. All rights reserved.
|
5 | * See LICENSE file in root directory for full license.
|
6 | */
|
7 |
|
8 |
|
9 | //------------------------------------------------------------------------------
|
10 | // Requirements
|
11 | //------------------------------------------------------------------------------
|
12 |
|
13 | const crossSpawn = require("cross-spawn")
|
14 | const getDescendentProcessInfo = require("ps-tree")
|
15 |
|
16 | //------------------------------------------------------------------------------
|
17 | // Helpers
|
18 | //------------------------------------------------------------------------------
|
19 |
|
20 | /**
|
21 | * Kills the new process and its sub processes.
|
22 | * @this ChildProcess
|
23 | * @returns {void}
|
24 | */
|
25 | function kill() {
|
26 | getDescendentProcessInfo(this.pid, (err, descendent) => {
|
27 | if (err) {
|
28 | return
|
29 | }
|
30 |
|
31 | for (const child of descendent) {
|
32 | try {
|
33 | process.kill(child.PID)
|
34 | }
|
35 | catch (_err) {
|
36 | // ignore.
|
37 | }
|
38 | }
|
39 | })
|
40 | }
|
41 |
|
42 | //------------------------------------------------------------------------------
|
43 | // Public Interface
|
44 | //------------------------------------------------------------------------------
|
45 |
|
46 | /**
|
47 | * Launches a new process with the given command.
|
48 | * This is almost same as `child_process.spawn`.
|
49 | *
|
50 | * This returns a `ChildProcess` instance.
|
51 | * `kill` method of the instance kills the new process and its sub processes.
|
52 | *
|
53 | * @param {string} command - The command to run.
|
54 | * @param {string[]} args - List of string arguments.
|
55 | * @param {object} options - Options.
|
56 | * @returns {ChildProcess} A ChildProcess instance of new process.
|
57 | * @private
|
58 | */
|
59 | module.exports = function spawn(command, args, options) {
|
60 | const child = crossSpawn(command, args, options)
|
61 | child.kill = kill
|
62 |
|
63 | return child
|
64 | }
|