Respond to messages from the parent process
556023
function messageHandler( msg ) {
  switch (msg.type) {
    case 'load'   : return handleLoadMsg(msg);
    case 'search' : return handleSearch(msg);
    case 'lookupById': return handleLookupById(msg);
    default       : logger.error('Unknown message:', msg);
  }
}
249881
def handle(self, msg):
        """"""
        debug_msg = ': {!r}'.format(msg) if self.debug else ''
        log.debug('request: %d bytes%s', len(msg), debug_msg)
        buf = io.BytesIO(msg)
        code, = util.recv(buf, '>B')
        if code not in self.methods:
            log.warning('Unsupported command: %s (%d)', msg_name(code), code)
            return failure()

        method = self.methods[code]
        log.debug('calling %s()', method.__name__)
        reply = method(buf=buf)
        debug_reply = ': {!r}'.format(reply) if self.debug else ''
        log.debug('reply: %d bytes%s', len(reply), debug_reply)
        return reply
798060
function spawn() {
  if(this.ps && this.ps.connected) return;
  this.ps = fork(
    runner, [], {execPath: path.basename(process.execPath)});
  this.ps.send({event: 'loglevel', level: log.level()});
}
81607
def processResponse(self, arg, replytype, **kw):
        
        if self.debug:
            log.msg('--->PROCESS REQUEST\n%s' %arg, debug=1)

        for h in self.handlers:
            arg.addCallback(h.processResponse, **kw)
            
        arg.addCallback(self.parseResponse, replytype)
506199
def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
        """"""
        inheaders = 1
        lines = data.split('\n')
        logger.info('---------- MESSAGE FOLLOWS ----------')
        for line in lines:
            # headers first
            if inheaders and not line:
                logger.info('X-Peer: %s' % peer[0])
                inheaders = 0
            logger.info(line)
        logger.info('------------ END MESSAGE ------------')
552190
def post_fork_child(self):
    """"""
    # Set the Exiter exception hook post-fork so as not to affect the pantsd processes exception
    # hook with socket-specific behavior. Note that this intentionally points the faulthandler
    # trace stream to sys.stderr, which at this point is still a _LoggerStream object writing to
    # the `pantsd.log`. This ensures that in the event of e.g. a hung but detached pantsd-runner
    # process that the stacktrace output lands deterministically in a known place vs to a stray
    # terminal window.
    # TODO: test the above!
    ExceptionSink.reset_exiter(self._exiter)

    ExceptionSink.reset_interactive_output_stream(sys.stderr.buffer if PY3 else sys.stderr)
    ExceptionSink.reset_signal_handler(DaemonSignalHandler())

    # Ensure anything referencing sys.argv inherits the Pailgun'd args.
    sys.argv = self._args

    # Set context in the process title.
    set_process_title('pantsd-runner [{}]'.format(' '.join(self._args)))

    # Broadcast our process group ID (in PID form - i.e. negated) to the remote client so
    # they can send signals (e.g. SIGINT) to all processes in the runners process group.
    NailgunProtocol.send_pid(self._socket, os.getpid())
    NailgunProtocol.send_pgrp(self._socket, os.getpgrp() * -1)

    # Stop the services that were paused pre-fork.
    for service in self._services.services:
      service.terminate()

    # Invoke a Pants run with stdio redirected and a proxied environment.
    with self.nailgunned_stdio(self._socket, self._env) as finalizer,\
         hermetic_environment_as(**self._env):
      try:
        # Setup the Exiter's finalizer.
        self._exiter.set_finalizer(finalizer)

        # Clean global state.
        clean_global_runtime_state(reset_subsystem=True)

        # Otherwise, conduct a normal run.
        runner = LocalPantsRunner.create(
          self._exiter,
          self._args,
          self._env,
          self._target_roots,
          self._graph_helper,
          self._options_bootstrapper
        )
        runner.set_start_time(self._maybe_get_client_start_time_from_env(self._env))

        # Re-raise any deferred exceptions, if present.
        self._raise_deferred_exc()

        runner.run()
      except KeyboardInterrupt:
        self._exiter.exit_and_fail('Interrupted by user.\n')
      except _GracefulTerminationException as e:
        ExceptionSink.log_exception(
          'Encountered graceful termination exception {}; exiting'.format(e))
        self._exiter.exit(e.exit_code)
      except Exception:
        # TODO: We override sys.excepthook above when we call ExceptionSink.set_exiter(). That
        # excepthook catches `SignalHandledNonLocalExit`s from signal handlers, which isn't
        # happening here, so something is probably overriding the excepthook. By catching Exception
        # and calling this method, we emulate the normal, expected sys.excepthook override.
        ExceptionSink._log_unhandled_exception_and_exit()
      else:
        self._exiter.exit(PANTS_SUCCEEDED_EXIT_CODE)
837151
def output_callback(self, line, kill_switch):
        """"""
        self.notifications += line + "\n"

        if "Initialization Sequence Completed" in line:
            self.started = True
        if "ERROR:" in line or "Cannot resolve host address:" in line:
            self.error = True
        if "process exiting" in line:
            self.stopped = True
589856
def _function_handler(function, args, kwargs, pipe):
    """"""
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    result = process_execute(function, *args, **kwargs)

    send_result(pipe, result)
201183
private void runMessage(MessageAmp msg)
  {
    try (OutboxAmp outbox = OutboxAmpFactory.newFactory().get()) {
      outbox.inbox(msg.inboxTarget());
      outbox.message(msg);
      
      //RampActor systemActor = null;
      StubAmp systemActor = _stub;
      
      msg.invoke(InboxExecutorBase.this, systemActor);
      
      while (! outbox.flushAndExecuteLast()) {
      }
    }
  }
850898
def send_message(self, output):
        

        file_system_event = None
        if self.my_action_input:
            file_system_event = self.my_action_input.file_system_event or None

        output_action = ActionInput(file_system_event,
                                    output,
                                    self.name,
                                    "*")

        Global.MESSAGE_DISPATCHER.send_message(output_action)
61244
function ProcessWatcher(pid, parent) {
    var self = this;

    this.dead = false;

    // check first if process is alive
    if (exports.alive(pid) === false) {
      process.nextTick(function () {
        self.dead = true;
        self.emit('dead');
      });
      return self;
    }

    // use disconnect to detect parent death
    if (parent && exports.support.disconnect) {
      var listen = function() {
        self.dead = true;
        self.stop();
        self.emit('dead');
      }

      parent.once('disconnect', listen);
      this.stop = parent.removeListener.bind(null, 'disconnect', listen);

      this.on('newListener', function (eventName) {
        if (eventName !== 'cycle') return;

        process.nextTick(function () {
          self.emit('cycle');
        });
      });

      return self;
    }

    // fallback to an setInterval try/catch check
    var timer = setInterval(function () {
      if (exports.alive(pid) === false) {
        self.dead = true;
        self.stop();
        self.emit('dead');
      }
      self.emit('cycle');
    });
    this.stop = clearInterval.bind(null, timer);
  }
747282
def request_echo(self, sock, msg):
        """"""
        return katcp.Message.reply(msg.name, "ok", *msg.arguments)
350230
function (emits, message, daemonPid) {
    var monitor = new Monitor(message, options, daemonPid, shutdown, child, function () {

      // emit events before starting child
      Object.keys(emits).forEach(function (name) {
        // skip the process event until the child spawns
        if (name === 'process') return;

        monitor.emit.apply(monitor, [name].concat( emits[name] ));
      });

      // spawn child when monitor is ready
      child.spawn();

      // start pumping streams to monitor
      child.pump(monitor);
    });

    // once the child has started emit the process event
    child.once('start', function () {
      monitor.pid.process = child.pid;
      monitor.emit.apply(monitor, ['process'].concat( emits.process ));
    });

    // relay stop and restart to process event on monitor
    child.on('stop', function () {
      monitor.pid.process = null;

      // Do not emit if the deamon is in restart mode
      if (daemonInRestart) return;
      monitor.emit('process', 'stop');
    });
    child.on('restart', function () {
      monitor.pid.process = child.pid;
      monitor.emit('process', 'restart');
    });
  }
812693
def msg message, wait = true
      cmd_msg message
      return false unless wait_for(last_label) if wait
      return @response_args
    end
511314
def set_process(self, process = None):
        
        if process is None:
            self.__process = None
        else:
            global Process      # delayed import
            if Process is None:
                from winappdbg.process import Process
            if not isinstance(process, Process):
                msg  = "Parent process must be a Process instance, "
                msg += "got %s instead" % type(process)
                raise TypeError(msg)
            self.__process = process
533429
def handler(self, reply):
        """"""
        data = reply.data
        while len(data):
            event, data = rq.EventField(None).parse_binary_value(data, self.display.display, None, None)
            if self.escape(event):  # Quit if this returns True
                self.stop()
            else:
                self._tap(event)
120033
function postMessage(msg) {
            addFilesPromise.done(function (ternModule) {
                // If an error came up during file handling, bail out now
                if (!_ternNodeDomain) {
                    return;
                }

                if (config.debug) {
                    console.debug("Sending message", msg);
                }
                _ternNodeDomain.exec("invokeTernCommand", msg);
            });
        }