1'use strict';
2
3const {
4  FunctionPrototypeBind,
5  SafeMap,
6} = primordials;
7
8const {
9  errnoException,
10} = require('internal/errors');
11
12const { signals } = internalBinding('constants').os;
13
14let Signal;
15const signalWraps = new SafeMap();
16
17function isSignal(event) {
18  return typeof event === 'string' && signals[event] !== undefined;
19}
20
21// Detect presence of a listener for the special signal types
22function startListeningIfSignal(type) {
23  if (isSignal(type) && !signalWraps.has(type)) {
24    if (Signal === undefined)
25      Signal = internalBinding('signal_wrap').Signal;
26    const wrap = new Signal();
27
28    wrap.unref();
29
30    wrap.onsignal = FunctionPrototypeBind(process.emit, process, type, type);
31
32    const signum = signals[type];
33    const err = wrap.start(signum);
34    if (err) {
35      wrap.close();
36      throw errnoException(err, 'uv_signal_start');
37    }
38
39    signalWraps.set(type, wrap);
40  }
41}
42
43function stopListeningIfSignal(type) {
44  const wrap = signalWraps.get(type);
45  if (wrap !== undefined && process.listenerCount(type) === 0) {
46    wrap.close();
47    signalWraps.delete(type);
48  }
49}
50
51module.exports = {
52  startListeningIfSignal,
53  stopListeningIfSignal,
54};
55