spawn-posix.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. }
  30. catch (_err) {
  31. // ignore.
  32. }
  33. }
  34. })
  35. }
  36. //------------------------------------------------------------------------------
  37. // Public Interface
  38. //------------------------------------------------------------------------------
  39. /**
  40. * Launches a new process with the given command.
  41. * This is almost same as `child_process.spawn`.
  42. *
  43. * This returns a `ChildProcess` instance.
  44. * `kill` method of the instance kills the new process and its sub processes.
  45. *
  46. * @param {string} command - The command to run.
  47. * @param {string[]} args - List of string arguments.
  48. * @param {object} options - Options.
  49. * @returns {ChildProcess} A ChildProcess instance of new process.
  50. * @private
  51. */
  52. module.exports = function spawn(command, args, options) {
  53. const child = crossSpawn(command, args, options)
  54. child.kill = kill
  55. return child
  56. }