Blocks for the nailgun subprocess to bind and emit a listening port in the nailgun stdout.
343088
def _await_socket(self, timeout):
    """"""
    with safe_open(self._ng_stdout, 'r') as ng_stdout:
      start_time = time.time()
      accumulated_stdout = ''
      while 1:
        # TODO: share the decreasing timeout logic here with NailgunProtocol.iter_chunks() by adding
        # a method to pants.util.contextutil!
        remaining_time = time.time() - (start_time + timeout)
        if remaining_time > 0:
          stderr = read_file(self._ng_stderr, binary_mode=True)
          raise self.InitialNailgunConnectTimedOut(
            timeout=timeout,
            stdout=accumulated_stdout,
            stderr=stderr,
          )

        readable, _, _ = select.select([ng_stdout], [], [], (-1 * remaining_time))
        if readable:
          line = ng_stdout.readline()                          # TODO: address deadlock risk here.
          try:
            return self._NG_PORT_REGEX.match(line).group(1)
          except AttributeError:
            pass
          accumulated_stdout += line
746957
def listen(identifier):
  

  context = Context()
  process = WebProcess(identifier)

  context.spawn(process)

  log.info("Launching PID %s", process.pid)

  return process, context
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');
    });
  }
470337
def post_fork_child(self, fingerprint, jvm_options, classpath, stdout, stderr):
    """"""
    java = SubprocessExecutor(self._distribution)

    subproc = java.spawn(classpath=classpath,
                         main='com.martiansoftware.nailgun.NGServer',
                         jvm_options=jvm_options,
                         args=[':0'],
                         stdin=safe_open('/dev/null', 'r'),
                         stdout=safe_open(self._ng_stdout, 'w'),
                         stderr=safe_open(self._ng_stderr, 'w'),
                         close_fds=True)

    self.write_pid(subproc.pid)
990517
async def listen(self, port, interface='0.0.0.0'):
        
        loop = asyncio.get_event_loop()
        listen = loop.create_datagram_endpoint(self._create_protocol,
                                               local_addr=(interface, port))
        log.info("Node %i listening on %s:%i",
                 self.node.long_id, interface, port)
        self.transport, self.protocol = await listen
        # finally, schedule refreshing table
        self.refresh_table()
1295754
def _run_tool(cmd, use_container=True, work_dir=None, log_file=None):
    
    if isinstance(cmd, (list, tuple)):
        cmd = " ".join([str(x) for x in cmd])
    cmd = utils.local_path_export(at_start=use_container) + cmd
    if log_file:
        cmd += " 2>&1 | tee -a %s" % log_file
    try:
        print("Running: %s" % cmd)
        subprocess.check_call(cmd, shell=True)
    finally:
        if use_container and work_dir:
            _chown_workdir(work_dir)
314003
def _init_listen_socket(self):
        
        self.debug("()")
        self._listen_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._listen_socket.setsockopt(
            socket.SOL_SOCKET,
            socket.SO_REUSEADDR,
            1
        )
        self._listen_socket.bind((self._listen_ip, self._listen_port))
        self._listening.append(self._listen_socket)
1121639
def listen_dep(self, target, timeout):
        
        return super(Device, self).listen_dep(target, timeout)
727507
function wrap() {
  var ports = this.compiledModule.ports;

  var incomingEmitter = new EventEmitter();
  var outgoingEmitter = new EventEmitter();

  var emit = incomingEmitter.emit.bind(incomingEmitter);

  Object.keys(ports).forEach(function(key) {
    outgoingEmitter.addListener(key, function() {
      var args = Array.prototype.slice.call(arguments)

      ports[key].send.apply(ports[key], args);
    });

    if (ports[key].subscribe) {
      ports[key].subscribe(function() {
        var args = Array.prototype.slice.call(arguments);
        args.unshift(key);

        emit.apply(incomingEmitter, args);
      });
    }
  });

  incomingEmitter.emit = outgoingEmitter.emit.bind(outgoingEmitter);;

  this.emitter = incomingEmitter;
  this.ports = this.compiledModule.ports;
}
890616
def listen(self, listenip="", listenport=DEF_TFTP_PORT,
               timeout=SOCK_TIMEOUT):
        """"""
        tftp_factory = TftpPacketFactory()

        # Don't use new 2.5 ternary operator yet
        # listenip = listenip if listenip else '0.0.0.0'
        if not listenip: listenip = '0.0.0.0'
        log.info("Server requested on ip %s, port %s" % (listenip, listenport))
        try:
            # FIXME - sockets should be non-blocking
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.sock.bind((listenip, listenport))
            _, self.listenport = self.sock.getsockname()
        except socket.error as err:
            # Reraise it for now.
            raise err

        self.is_running.set()

        log.info("Starting receive loop...")
        while True:
            log.debug("shutdown_immediately is %s" % self.shutdown_immediately)
            log.debug("shutdown_gracefully is %s" % self.shutdown_gracefully)
            if self.shutdown_immediately:
                log.warning("Shutting down now. Session count: %d" %
                         len(self.sessions))
                self.sock.close()
                for key in self.sessions:
                    self.sessions[key].end()
                self.sessions = []
                break

            elif self.shutdown_gracefully:
                if not self.sessions:
                    log.warning("In graceful shutdown mode and all "
                             "sessions complete.")
                    self.sock.close()
                    break

            # Build the inputlist array of sockets to select() on.
            inputlist = []
            inputlist.append(self.sock)
            for key in self.sessions:
                inputlist.append(self.sessions[key].sock)

            # Block until some socket has input on it.
            log.debug("Performing select on this inputlist: %s", inputlist)
            try:
                readyinput, readyoutput, readyspecial = \
                        select.select(inputlist, [], [], SOCK_TIMEOUT)
            except select.error as err:
                if err[0] == EINTR:
                    # Interrupted system call
                    log.debug("Interrupted syscall, retrying")
                    continue
                else:
                    raise

            deletion_list = []

            # Handle the available data, if any. Maybe we timed-out.
            for readysock in readyinput:
                # Is the traffic on the main server socket? ie. new session?
                if readysock == self.sock:
                    log.debug("Data ready on our main socket")
                    buffer, (raddress, rport) = self.sock.recvfrom(MAX_BLKSIZE)

                    log.debug("Read %d bytes", len(buffer))

                    if self.shutdown_gracefully:
                        log.warning("Discarding data on main port, "
                                 "in graceful shutdown mode")
                        continue

                    # Forge a session key based on the client's IP and port,
                    # which should safely work through NAT.
                    key = "%s:%s" % (raddress, rport)

                    if not key in self.sessions:
                        log.debug("Creating new server context for "
                                     "session key = %s" % key)
                        self.sessions[key] = TftpContextServer(raddress,
                                                               rport,
                                                               timeout,
                                                               self.root,
                                                               self.dyn_file_func,
                                                               self.upload_open)
                        try:
                            self.sessions[key].start(buffer)
                        except TftpException as err:
                            deletion_list.append(key)
                            log.error("Fatal exception thrown from "
                                      "session %s: %s" % (key, str(err)))
                    else:
                        log.warning("received traffic on main socket for "
                                 "existing session??")
                    log.info("Currently handling these sessions:")
                    for session_key, session in list(self.sessions.items()):
                        log.info("    %s" % session)

                else:
                    # Must find the owner of this traffic.
                    for key in self.sessions:
                        if readysock == self.sessions[key].sock:
                            log.debug("Matched input to session key %s"
                                % key)
                            try:
                                self.sessions[key].cycle()
                                if self.sessions[key].state == None:
                                    log.info("Successful transfer.")
                                    deletion_list.append(key)
                            except TftpException as err:
                                deletion_list.append(key)
                                log.error("Fatal exception thrown from "
                                          "session %s: %s"
                                          % (key, str(err)))
                            # Break out of for loop since we found the correct
                            # session.
                            break
                    else:
                        log.error("Can't find the owner for this packet. "
                                  "Discarding.")

            log.debug("Looping on all sessions to check for timeouts")
            now = time.time()
            for key in self.sessions:
                try:
                    self.sessions[key].checkTimeout(now)
                except TftpTimeout as err:
                    log.error(str(err))
                    self.sessions[key].retry_count += 1
                    if self.sessions[key].retry_count >= TIMEOUT_RETRIES:
                        log.debug("hit max retries on %s, giving up" %
                            self.sessions[key])
                        deletion_list.append(key)
                    else:
                        log.debug("resending on session %s" % self.sessions[key])
                        self.sessions[key].state.resendLast()

            log.debug("Iterating deletion list.")
            for key in deletion_list:
                log.info('')
                log.info("Session %s complete" % key)
                if key in self.sessions:
                    log.debug("Gathering up metrics from session before deleting")
                    self.sessions[key].end()
                    metrics = self.sessions[key].metrics
                    if metrics.duration == 0:
                        log.info("Duration too short, rate undetermined")
                    else:
                        log.info("Transferred %d bytes in %.2f seconds"
                            % (metrics.bytes, metrics.duration))
                        log.info("Average rate: %.2f kbps" % metrics.kbps)
                    log.info("%.2f bytes in resent data" % metrics.resent_bytes)
                    log.info("%d duplicate packets" % metrics.dupcount)
                    log.debug("Deleting session %s" % key)
                    del self.sessions[key]
                    log.debug("Session list is now %s" % self.sessions)
                else:
                    log.warning(
                        "Strange, session %s is not on the deletion list" % key)

        self.is_running.clear()

        log.debug("server returning from while loop")
        self.shutdown_gracefully = self.shutdown_immediately = False
500100
function listen(self, address, port, addressType, backlog, exclusive) {
    /* TODO Index servers by a self-assigned identifier and the process
     * identifier so messages intended for previous instances do not pass
     * through. */
    servers[port] = self; // Index servers by port.
    self._port = port; // Remember the requested port for close.
    process.send({
        cmd: 'CLUSTER_LISTEN',
        port: port,
        address: address, // For confirmation purposes only.
        addressType: addressType, // We allow the supervisor to infer the address type.
        backlog: backlog, // Used to confirm uniformity of worker requests.
        exclusive: exclusive // TODO use this on the other end
    });
}
748432
function bindSocket(io, indicator) {
    Object.keys(indicator.watch).forEach((key) => {
        let eventName = indicator.watch[key];
        indicator.on(eventName, (msg) => io.emit(eventName, msg));
    });
}
152616
def spawn_process(self, target, *args):
        
        p = Process(target=target, args=args)
        p.daemon = True
        if target == worker:
            p.daemon = Conf.DAEMONIZE_WORKERS
            p.timer = args[2]
            self.pool.append(p)
        p.start()
        return p
589288
def spawn_processes(self):
        """"""
        for port in self.ports_to_spawn:
            process = self.spawn_process(port)
            process.start()
            self.children.append(process)
492949
def _subthread_handle_accepted(self, client):
        

        conn, addr = client
        if self.handle_incoming(conn, addr):
            logging.info('Accepted connection from client: {}'.format(addr))
            conn.setblocking(False)
            self.clients[conn] = addr
            self.register(conn)
        else:
            logging.info('Refused connection from client: {}'.format(addr))
            self.disconnect(conn)
202908
function setupListener (host_port, listenerDone) {

            const hp = /^\[?([^\]]+)\]?:(\d+)$/.exec(host_port);
            if (!hp) return listenerDone(
                new Error('Invalid "listen" format in smtp.ini'));

            const host = hp[1];
            const port = parseInt(hp[2], 10);

            Server.get_smtp_server(host, port, inactivity_timeout, (server) => {
                if (!server) return listenerDone();

                server.notes = Server.notes;
                if (Server.cluster) server.cluster = Server.cluster;

                server
                    .on('listening', function () {
                        const addr = this.address();
                        logger.lognotice(`Listening on ${addr.address}:${addr.port}`);
                        listenerDone();
                    })
                    .on('close', () => {
                        logger.loginfo(`Listener ${host}:${port} stopped`);
                    })
                    .on('error', e => {
                        if (e.code !== 'EAFNOSUPPORT') return listenerDone(e);
                        // Fallback from IPv6 to IPv4 if not supported
                        // But only if we supplied the default of [::0]:25
                        if (/^::0/.test(host) && Server.default_host) {
                            server.listen(port, '0.0.0.0', 0);
                            return;
                        }
                        // Pass error to callback
                        listenerDone(e);
                    })
                    .listen(port, host, 0);
            });
        }
630336
def do_attach(self, arg):
        
        if self.cmdprefix:
            raise CmdError("prefix not allowed")
        targets = self.input_process_list( self.split_tokens(arg, 1) )
        if not targets:
            print("Error: missing parameters")
        else:
            debug = self.debug
            for pid in targets:
                try:
                    debug.attach(pid)
                    print("Attached to process (%d)" % pid)
                except Exception:
                    print("Error: can't attach to process (%d)" % pid)