// _pidAlive tests whether a process is alive or not
511322
func _pidAlive(pid int) bool {
	h, err := syscall.OpenProcess(processDesiredAccess, false, uint32(pid))
	if err != nil {
		return false
	}

	var ec uint32
	if e := syscall.GetExitCodeProcess(h, &ec); e != nil {
		return false
	}

	return ec == exit_STILL_ACTIVE
}
753474
func (d *Daemon) Pid() (int, error) {
	pid, err := ioutil.ReadFile(d.PidFileName)
	if err != nil {
		return 0, err
	}
	p, err := strconv.Atoi(string(bytes.TrimSpace(pid)))
	if err != nil {
		return 0, fmt.Errorf("%s: invalid process id", d.PidFileName)
	}
	return p, nil
}
135943
func KillPID(pidFilename string) bool {
	PIDFilename(&pidFilename)
	defer os.Remove(pidFilename)

	pid, current_status := ReadPIDFile(pidFilename)
	if current_status {
		if err := syscall.Kill(pid, 15); err == nil {
			return true
		}
	}
	return false
}
1073254
func (s *service) Pids(ctx context.Context, r *taskAPI.PidsRequest) (*taskAPI.PidsResponse, error) {
	container, err := s.getContainer()
	if err != nil {
		return nil, err
	}
	pids, err := s.getContainerPids(ctx, r.ID)
	if err != nil {
		return nil, errdefs.ToGRPC(err)
	}
	var processes []*task.ProcessInfo
	for _, pid := range pids {
		pInfo := task.ProcessInfo{
			Pid: pid,
		}
		for _, p := range container.ExecdProcesses() {
			if p.Pid() == int(pid) {
				d := &options.ProcessDetails{
					ExecID: p.ID(),
				}
				a, err := typeurl.MarshalAny(d)
				if err != nil {
					return nil, errors.Wrapf(err, "failed to marshal process %d info", pid)
				}
				pInfo.Info = a
				break
			}
		}
		processes = append(processes, &pInfo)
	}
	return &taskAPI.PidsResponse{
		Processes: processes,
	}, nil
}
915145
func IsInter(data sort.Interface, pivot int) bool {
	i, j, k, l := 0, pivot, pivot, data.Len()
	for i < k && j < l {
		switch {
		case data.Less(i, j):
			i++
		case data.Less(j, i):
			j++
		default:
			return true
		}
	}
	return false
}
102216
func Status() (isRunning bool, pr *os.Process, e error) {
	const errLoc = "daemonigo.Status()"
	var (
		err  error
		file *os.File
	)

	file, err = os.Open(PidFile)
	if err != nil {
		if !os.IsNotExist(err) {
			e = fmt.Errorf(
				"%s: could not open PID file, reason -> %s",
				errLoc, err.Error(),
			)
		}
		return
	}
	defer file.Close()
	fd := int(file.Fd())
	if err = syscall.Flock(
		fd, syscall.LOCK_EX|syscall.LOCK_NB,
	); err != syscall.EWOULDBLOCK {
		if err == nil {
			syscall.Flock(fd, syscall.LOCK_UN)
		} else {
			e = fmt.Errorf(
				"%s: PID file locking attempt failed, reason -> %s",
				errLoc, err.Error(),
			)
		}
		return
	}

	isRunning = true
	var n, pid int
	content := make([]byte, 128)
	n, err = file.Read(content)
	if err != nil && err != io.EOF {
		e = fmt.Errorf(
			"%s: could not read from PID file, reason -> %s",
			errLoc, err.Error(),
		)
		return
	}
	pid, err = strconv.Atoi(string(content[:n]))
	if n < 1 || err != nil {
		e = fmt.Errorf(
			"%s: bad PID format, PID file is possibly corrupted", errLoc,
		)
		return
	}
	pr, err = os.FindProcess(pid)
	if err != nil {
		e = fmt.Errorf(
			"%s: cannot find process by PID, reason -> %s", errLoc, err.Error(),
		)
	}

	return
}
1334078
func (c *cluster) IsCleanedOut(ctx context.Context, serverID string) (bool, error) {
	r, err := c.NumberOfServers(ctx)
	if err != nil {
		return false, WithStack(err)
	}
	for _, id := range r.CleanedServerIDs {
		if id == serverID {
			return true, nil
		}
	}
	return false, nil
}
1163515
func pidState(pid int) (state.State, error) {
	if pid == 0 {
		return state.Stopped, nil
	}
	p, err := ps.FindProcess(pid)
	if err != nil {
		return state.Error, err
	}
	if p == nil {
		log.Debugf("hyperkit pid %d missing from process table", pid)
		return state.Stopped, nil
	}
	// hyperkit or com.docker.hyper
	if !strings.Contains(p.Executable(), "hyper") {
		log.Debugf("pid %d is stale, and is being used by %s", pid, p.Executable())
		return state.Stopped, nil
	}
	return state.Running, nil
}
109884
func promptInteractive(upgradedHostId, upgradedHostName string) (stopPrompting bool, err error) {
	stopPrompting = false
	scanner := bufio.NewScanner(os.Stdin)
	if upgradedHostName != "" {
		glog.Infof("Pausing after finished %q, node %q", upgradedHostId, upgradedHostName)
	} else {
		glog.Infof("Pausing after finished %q", upgradedHostId)
	}
	fmt.Print("Continue? (Y)es, (N)o, (A)lwaysYes: [Y] ")
	scanner.Scan()
	err = scanner.Err()
	if err != nil {
		glog.Infof("unable to interpret input: %v", err)
		return stopPrompting, err
	}
	val := scanner.Text()
	val = strings.TrimSpace(val)
	val = strings.ToLower(val)
	switch val {
	case "n":
		glog.Info("User signaled to stop")
		os.Exit(3)
	case "a":
		glog.Info("Always Yes, stop prompting for rest of hosts")
		stopPrompting = true
	}
	return stopPrompting, err
}
653116
func (u *uidProcessor) Resync(ctx context.Context, e *common.EventInfo) error {

	uids := u.netcls.ListAllCgroups("")
	for _, uid := range uids {

		if _, ok := ignoreNames[uid]; ok {
			continue
		}

		processesOfUID := u.netcls.ListAllCgroups(uid)
		activePids := []int32{}

		for _, pid := range processesOfUID {
			if _, ok := ignoreNames[pid]; ok {
				continue
			}

			cgroupPath := uid + "/" + pid
			pidlist, _ := u.netcls.ListCgroupProcesses(cgroupPath)
			if len(pidlist) == 0 {
				if err := u.netcls.DeleteCgroup(cgroupPath); err != nil {
					zap.L().Warn("Unable to delete cgroup",
						zap.String("cgroup", cgroupPath),
						zap.Error(err),
					)
				}
				continue
			}

			iPid, _ := strconv.Atoi(pid)
			activePids = append(activePids, int32(iPid))
		}

		if len(activePids) == 0 {
			if err := u.netcls.DeleteCgroup(uid); err != nil {
				zap.L().Warn("Unable to delete cgroup",
					zap.String("cgroup", uid),
					zap.Error(err),
				)
			}
			continue
		}

		event := &common.EventInfo{
			PID:    activePids[0],
			PUID:   uid,
			PUType: common.UIDLoginPU,
		}

		if err := u.createAndStart(ctx, event, true); err != nil {
			zap.L().Error("Can not synchronize user", zap.String("user", uid))
		}

		for i := 1; i < len(activePids); i++ {
			event := &common.EventInfo{
				PID:    activePids[i],
				PUID:   uid,
				PUType: common.UIDLoginPU,
			}
			if err := u.createAndStart(ctx, event, true); err != nil {
				zap.L().Error("Can not synchronize user", zap.String("user", uid))
			}
		}
	}

	return nil
}
271231
func PidExists(pid int32) (bool, error) {
	abool, err := process.PidExists(pid)

	return abool, err
}
979939
func existsPID(pid int) bool {
	_, err := os.FindProcess(pid)
	if err != nil {
		return false
	}

	return true
}
13128
func (p *execProcess) TerminateNicely(killGracePeriod time.Duration) error {
	// Make sure process is being waited on for process state reaping to occur
	// as to avoid forcibly killing the process after killGracePeriod
	if p.waitCh == nil {
		panic("TerminateNicely() must be called after Wait()")
	}

	err := p.signalGroup(syscall.SIGTERM)
	if err != nil {
		return bosherr.WrapErrorf(err, "Sending SIGTERM to process group %d", p.pgid)
	}

	terminatedCh := make(chan struct{})
	stopCheckingTerminatedCh := make(chan struct{})

	go func() {
		for p.groupExists() {
			select {
			case <-time.After(500 * time.Millisecond):
				// nothing to do
			case <-stopCheckingTerminatedCh:
				return
			}
		}

		close(terminatedCh)
	}()

	select {
	case <-terminatedCh:
		// nothing to do

	case <-time.After(killGracePeriod):
		close(stopCheckingTerminatedCh)

		err = p.signalGroup(syscall.SIGKILL)
		if err != nil {
			return bosherr.WrapErrorf(err, "Sending SIGKILL to process group %d", p.pgid)
		}
	}

	// It takes some time for the process to disappear
	for i := 0; i < 20; i++ {
		if !p.groupExists() {
			return nil
		}
		time.Sleep(500 * time.Millisecond)
	}

	return bosherr.Errorf("Failed to kill process after grace timeout (PID %d)", p.pid)
}
730422
func (p *pidFileOption) Apply(server *Server) {
	if p.newValue == "" {
		return
	}
	if err := server.logPid(); err != nil {
		server.Errorf("Failed to write pidfile: %v", err)
	}
	server.Noticef("Reloaded: pid_file = %v", p.newValue)
}
136439
func findProcess(pid int) (*os.Process, error) {
	// FindProcess never fails on unix-like systems.
	p, err := os.FindProcess(pid)
	if err != nil {
		return nil, err
	}

	// On Unix-like systems, we can verify a process is alive by sending
	// a 0 signal. This will do nothing to the process but will still
	// return errors if the process is gone.
	err = p.Signal(syscall.Signal(0))
	if err == nil {
		return p, nil
	}

	return nil, fmt.Errorf("process %d is dead or running as another user", pid)
}
933607
func (n PidMode) IsContainer() bool {
	parts := strings.SplitN(string(n), ":", 2)
	return len(parts) > 1 && parts[0] == "container"
}
1189219
func WritePidFile(pidFile string) error {
	if pidFile == "" {
		return nil
	}
	pid := []byte(strconv.Itoa(os.Getpid()) + "\n")
	return ioutil.WriteFile(pidFile, pid, 0644)
}