spawn-posix.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. 'use strict'
  8. // ------------------------------------------------------------------------------
  9. // Requirements
  10. // ------------------------------------------------------------------------------
  11. const crossSpawn = require('cross-spawn')
  12. const getDescendentProcessInfo = require('pidtree')
  13. // ------------------------------------------------------------------------------
  14. // Helpers
  15. // ------------------------------------------------------------------------------
  16. /**
  17. * Kills the new process and its sub processes.
  18. * @this ChildProcess
  19. * @returns {void}
  20. */
  21. function kill () {
  22. getDescendentProcessInfo(this.pid, { root: true }, (err, pids) => {
  23. if (err) {
  24. return
  25. }
  26. for (const pid of pids) {
  27. try {
  28. process.kill(pid)
  29. } catch (_err) {
  30. // ignore.
  31. }
  32. }
  33. })
  34. }
  35. // ------------------------------------------------------------------------------
  36. // Public Interface
  37. // ------------------------------------------------------------------------------
  38. /**
  39. * Launches a new process with the given command.
  40. * This is almost same as `child_process.spawn`.
  41. *
  42. * This returns a `ChildProcess` instance.
  43. * `kill` method of the instance kills the new process and its sub processes.
  44. *
  45. * @param {string} command - The command to run.
  46. * @param {string[]} args - List of string arguments.
  47. * @param {object} options - Options.
  48. * @returns {ChildProcess} A ChildProcess instance of new process.
  49. * @private
  50. */
  51. module.exports = function spawn (command, args, options) {
  52. const child = crossSpawn(command, args, options)
  53. child.kill = kill
  54. return child
  55. }