TODO: identifiy the monitor process
353114
def find_applications_by_app_name(app_name)
      pids = []

      begin
        x = `ps auxw | grep -v grep | awk '{print $2, $11, $12}' | grep #{app_name}`
        if x && x.chomp!
          processes = x.split(/\n/).compact
          processes = processes.delete_if do |p|
            _pid, name, add = p.split(/\s/)
            # We want to make sure that the first part of the process name matches
            # so that app_name matches app_name_22

            app_name != name[0..(app_name.length - 1)] and not add.include?(app_name)
          end
          pids = processes.map { |p| p.split(/\s/)[0].to_i }
        end
        rescue ::Exception
      end

      pids.map do |f|
        app = Application.new(self, {}, PidMem.existing(f))
        setup_app(app)
        app
      end
    end
638514
function monitor() {
    if(!child.pid) {
      // If the number of periodic starts exceeds the max, kill the process
      if (starts >= options.maxRetries) {
        if ((Date.now() - startTime) > maxMilliseconds) {
          console.error(
            `Too many restarts within the last ${maxMilliseconds / 1000} seconds. Please check the script.`
          )
          process.exit(1)
        }
      }

      setTimeout(() => {
        wait = wait * options.growPercentage
        attempts += 1;
        if (attempts > options.maxRestarts && options.maxRestarts >= 0){
          console.error(
            `${options.name} will not be restarted because the maximum number of total restarts has been exceeded.`
          )
          process.exit()
        } else {
          launch()
        }
      }, wait)
    } else {
      attempts = 0
      wait = options.restartDelay * 1000
    }
  }
848861
private int processId(final java.lang.Process process) {
    int processId = 0;
    try {
      final Field f = process.getClass().getDeclaredField("pid");
      f.setAccessible(true);

      processId = f.getInt(process);
    } catch (final Throwable e) {
      e.printStackTrace();
    }

    return processId;
  }
1163661
function getProcessName(app, processName, index) {
  if (index > 0) {
    return app + '-' + processName + '-' + index;
  } else {
    return app + '-' + processName;
  }
}
284705
public void monitor(Monitor target) {
        log.info("starting monitor: {}", target);

        try {
            target.getMonitorDriver(props, configService).run();

        } catch (Exception e) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            PrintStream error = new PrintStream(out);

            error.println("Error in MonitorsDriver: " + e.getMessage());
            e.printStackTrace(error);

            error.flush();
            IOUtils.closeQuietly(out);

            String msg = new String(out.toByteArray());
            log.error(msg);
            sendEmail("Management Console Monitors Error", msg);
        }
    }
290240
def __get_pid_by_scanning(self):
        ''
        dwProcessId = None
        dwThreadId = self.get_tid()
        with win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPTHREAD) as hSnapshot:
            te = win32.Thread32First(hSnapshot)
            while te is not None:
                if te.th32ThreadID == dwThreadId:
                    dwProcessId = te.th32OwnerProcessID
                    break
                te = win32.Thread32Next(hSnapshot)
        if dwProcessId is None:
            msg = "Cannot find thread ID %d in any process" % dwThreadId
            raise RuntimeError(msg)
        return dwProcessId
356723
def __get_pid_and_tid(self):
        ""
        self.dwThreadId, self.dwProcessId = \
                            win32.GetWindowThreadProcessId(self.get_handle())
557090
def pid
      return nil unless is_window?
      process_id = 0.chr * 4
      GetWindowThreadProcessId(handle, process_id)
      process_id = process_id.unpack('L').first
    end
1182618
def status(self):
        

        if self.pid is None:
            self.pid = self.read_pid()
        if self.pid is None:
            sp = BackgroundProcess.objects.filter(pk=1).first()
            if sp:
                self.pid = sp.pid
        if self.pid is None or self.pid == 0:
            self.stderr.write("%s: can't determine process id exiting.\n" % datetime.now().isoformat(' '))
            return False
        if self.pid != getpid():
            # calling from outside the daemon instance
            try:
                kill(self.pid, signal.SIGUSR2)
                return True
            except OSError as e:
                if e.errno == errno.ESRCH:
                    return False
                else:
                    return False

        process_list = []
        for process in BackgroundProcess.objects.filter(parent_process__pk=self.process_id):
            process_list.append(process)
            process_list += list(process.backgroundprocess_set.filter())
        for process in process_list:
            logger.debug('%s, parrent process_id %d' % (self.label, process.parent_process.pk))
            logger.debug('%s, process_id %d' % (self.label, self.process_id))
5269
private Long getMinTransformedProcessId(Long loadedProcessId) {
        ProcessMonitor processMonitor = ArbitrateFactory.getInstance(getPipelineId(), ProcessMonitor.class);
        List<Long> processIds = processMonitor.getCurrentProcessIds();
        // 如果需要当前node处理当前process的load时，rpc请求一定会将对应的stage状态发到这机器上，并保存到progress中
        if (!CollectionUtils.isEmpty(processIds) && !CollectionUtils.isEmpty(progress)) {
            // 上一次load成功的在当前的processId中不存在，可能有两种情况:
            // 1. zk还未将数据通知过来，当前current processIds还是为老版本的值
            // 2. processId已经被删除，比如好久没有数据同步了，定时触发时发觉列表一直为空
            // if (loadedProcessId != null && !processIds.contains(loadedProcessId)) {
            // // 强制刷新一次，不过也可能是刷到老版本的值，杭州leader还没同步到美国
            // processIds = processMonitor.getCurrentProcessIds(true);
            // }

            Long result = null;
            // 做的一个优化，如果上一个processId load成功是在本机，直接忽略
            // 因为存在一个问题：比如两个process，都先完成了T模块，然后逐个触发L模块，此时第二个process需要等zookeeper回调watcher时才会被触发
            for (Long processId : processIds) {
                if (loadedProcessId == null || processId > loadedProcessId) {
                    result = processId;
                    break;
                }
            }

            // 如果不存在符合>loadedProcessId的记录，直接假设下一个processId就是上一个id+1
            // 因为processId目前的机制永远只会递增
            if (result == null) {
                result = loadedProcessId + 1;
            }

            if (result != null) {
                StageProgress stage = progress.get(result);
                if (stage != null && stage.getStage().isTransform()) {
                    return result;
                } else {
                    logger.info("rpc compute [{}] but stage [{}]", result, stage == null ? null : stage.getStage());
                    return null;
                }
            }
        }

        return null;
    }
1135380
public void startWatching() {
        try {
            final List<MonitorLine> lines = getSource().getLastLine(getInitialCount());
            actual = null;
            updateLines(lines);
        } catch (Exception e) {
            notifyObservers(e);
        }
    }
60569
def createMonitor(self, callback=None, errback=None, **kwargs):
        
        import ns1.monitoring
        monitor = ns1.monitoring.Monitor(self.config)
        return monitor.create(callback=callback, errback=errback, **kwargs)
1003196
def start_log_monitor(self):
        """"""
        stdout_file, stderr_file = self.new_log_files("log_monitor")
        process_info = ray.services.start_log_monitor(
            self.redis_address,
            self._logs_dir,
            stdout_file=stdout_file,
            stderr_file=stderr_file,
            redis_password=self._ray_params.redis_password)
        assert ray_constants.PROCESS_TYPE_LOG_MONITOR not in self.all_processes
        self.all_processes[ray_constants.PROCESS_TYPE_LOG_MONITOR] = [
            process_info
        ]
161314
private void sawMonitorEnter(int pc) {
        monitorSyncPCs.add(Integer.valueOf(pc));

        ScopeBlock sb = new ScopeBlock(pc, Integer.MAX_VALUE);
        sb.setSync();
        rootScopeBlock.addChild(sb);
    }
312170
static ProgressMonitor getMonitor() {
        return new ProgressMonitor() {

            @Override
            public void message(String msg) {
                System.out.println(msg + "...");
            }

            @Override
            public void progress(int prog) {
                if ("\\".equals(System.getProperty("file.separator"))) {
                    System.out.print("\b\b\b\b\b\b\b\b\b");
                }
                else {
                    System.out.print("\r         \r");
                }
                if (prog >= 100)
                    System.out.println(" --> Done");
                else if (prog <= 0) // don't report zero progress since it may indicate unknown
                    System.out.print(" ... ");
                else
                    System.out.printf(" --> %3d%%", prog);
            }

        };
    }
887935
def watchdog(sleep_interval):
    
    mtimes = {}
    worker_process = restart_with_reloader()
    signal.signal(
        signal.SIGTERM, lambda *args: kill_program_completly(worker_process)
    )
    signal.signal(
        signal.SIGINT, lambda *args: kill_program_completly(worker_process)
    )
    while True:
        for filename in _iter_module_files():
            try:
                mtime = os.stat(filename).st_mtime
            except OSError:
                continue

            old_time = mtimes.get(filename)
            if old_time is None:
                mtimes[filename] = mtime
                continue
            elif mtime > old_time:
                kill_process_children(worker_process.pid)
                worker_process.terminate()
                worker_process = restart_with_reloader()
                mtimes[filename] = mtime
                break

        sleep(sleep_interval)
842530
private Counter initAndRegisterCounter(String name) {
        BasicCounter counter = new BasicCounter(MonitorConfig.builder(name).build());
        DefaultMonitorRegistry.getInstance().register(counter);
        return counter;
    }