diff --git a/doc/api/process.md b/doc/api/process.md index bdadaaea88c1..445e6a5af088 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -95,6 +95,13 @@ log, either periodically (probably best for long-running programs, allowing you to clear the map, which in the case of a very buggy program could grow indefinitely) or upon process exit (more convenient for scripts). +## Event: 'spawn' + +Emitted whenever a process calls the internal `child_process.spawn()` and assign +the child a `pid`. This is useful for bookkeeping - especially for subsequent +calls to `process.kill()`, in case no reference to `child` was held and hence +`child.kill()` is not an option. + ## Event: 'uncaughtException' The `'uncaughtException'` event is emitted when an exception bubbles all the diff --git a/lib/internal/child_process.js b/lib/internal/child_process.js index ff26e8b75ab5..5cef0f07fb83 100644 --- a/lib/internal/child_process.js +++ b/lib/internal/child_process.js @@ -303,6 +303,7 @@ ChildProcess.prototype.spawn = function(options) { } this.pid = this._handle.pid; + process.emit('spawn', this.pid); stdio.forEach(function(stdio, i) { if (stdio.type === 'ignore') return; diff --git a/test/parallel/test-process-emit.js b/test/parallel/test-process-emit.js index f4f6d546f15c..ca249a12db78 100644 --- a/test/parallel/test-process-emit.js +++ b/test/parallel/test-process-emit.js @@ -1,6 +1,7 @@ 'use strict'; const common = require('../common'); const assert = require('assert'); +const spawn = require('child_process').spawn const sym = Symbol(); process.on('normal', common.mustCall((data) => { @@ -20,3 +21,7 @@ process.emit(sym, 'symbolData'); process.emit('SIGPIPE', 'signalData'); assert.strictEqual(isNaN(process._eventsCount), false); + +process.on('spawn', common.mustCall((pid) => { + assert.strictEqual(isNaN(pid), false); +}))