/*
returns PID from pidfile and status of the process if stil running
*/
504118
func ReadPIDFile(pidFilename string) (int, bool) {
	PIDFilename(&pidFilename)

	pid_bytes, _ := ioutil.ReadFile(pidFilename)
	pid_string := strings.TrimSpace(string(pid_bytes))
	pid, _ := strconv.Atoi(pid_string)
	if pid == 0 {
		return -1, false
	}

	if err := syscall.Kill(pid, 0); err == nil {
		return pid, true
	}
	return pid, false
}
564677
func pidWait(pid int) error {
	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()

	for range ticker.C {
		if !pidAlive(pid) {
			break
		}
	}

	return nil
}
108540
func (s *Service) getExecProcess(id string) (rproc.Process, error) {
	s.mu.Lock()
	defer s.mu.Unlock()

	p := s.processes[id]
	if p == nil {
		return nil, errdefs.ToGRPCf(errdefs.ErrNotFound, "process %s does not exist", id)
	}
	return p, nil
}
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
}
452696
func (m *MockRuntimeReader) Pid() int {
	ret := m.ctrl.Call(m, "Pid")
	ret0, _ := ret[0].(int)
	return ret0
}
942962
func (s *RPCServer) ProcessPid(arg ProcessPidIn, out *ProcessPidOut) error {
	out.Pid = s.debugger.ProcessPid()
	return nil
}
1189219
func WritePidFile(pidFile string) error {
	if pidFile == "" {
		return nil
	}
	pid := []byte(strconv.Itoa(os.Getpid()) + "\n")
	return ioutil.WriteFile(pidFile, pid, 0644)
}
824379
func WritePidFile(pid int, filename string) error {
	pidString := strconv.Itoa(pid)
	pidFile, err := os.OpenFile(filename, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	defer pidFile.Close()
	_, err = pidFile.WriteString(pidString)
	return err
}
505235
func isWaitable(pid int) (bool, error) {
	si := &siginfo{}
	_, _, e := unix.Syscall6(unix.SYS_WAITID, _P_PID, uintptr(pid), uintptr(unsafe.Pointer(si)), unix.WEXITED|unix.WNOWAIT|unix.WNOHANG, 0, 0)
	if e != 0 {
		return false, os.NewSyscallError("waitid", e)
	}

	return si.si_pid != 0, nil
}
653955
func findProcessWithPID(pid int) (ps.Process, error) {
	matchPID := func(p ps.Process) bool { return p.Pid() == pid }
	procs, err := findProcessesWithFn(ps.Processes, matchPID, 1)
	if err != nil {
		return nil, err
	}
	if len(procs) == 0 {
		return nil, nil
	}
	return procs[0], nil
}
1335594
func GetProcessStats(pid int) (*ProcessStats, error) {
	p := &ProcessStats{}

	// Load and Parse /proc/{pid}/stat to get all the data we need
	filename := fmt.Sprintf("/proc/%d/stat", pid)
	b, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, fmt.Errorf("failed to read process stats: %v", err)
	}
	fields := strings.Fields(string(b))
	// Magic number is the total fields in the file, as documented by proc.
	if len(fields) != 52 {
		return nil, fmt.Errorf("failed to parse proc stat file")
	}

	// Calculate the ticks for the process. Indexes based on the proc(5) manpage
	// for user/kernel ticks, as well as its children's user/kernel ticks.
	totalTicks, err := sum(fields[13], fields[14], fields[15], fields[16])
	if err != nil {
		return nil, fmt.Errorf("failed to calculate process CPU usage: %v", err)
	}

	// use float in going from ticks to time to ensure we preserve granularity
	// below 1 second.
	p.CpuNs = time.Duration(float64(totalTicks) / float64(ticks) * float64(time.Second))

	// Calculate the total resident set pages/size. Index based on man proc(5).
	totalPages, err := sum(fields[23])
	if err != nil {
		return nil, err
	}
	p.RssBytes = totalPages * pagesize

	return p, nil
}
339650
func GetProcStat(pid int) (*ProcStat, error) {
	stat := ProcStat{}

	// read in the stat
	data, err := ioutil.ReadFile(fmt.Sprintf(procDir+"%d/stat", pid))
	if err != nil {
		return nil, err
	}
	fields := strings.Fields(string(data))

	// the first field contains the PID
	if len(fields) < 1 {
		return nil, fmt.Errorf("less than 1 field")
	}
	if err := parseInt(fields[0], &stat.Pid); err != nil {
		return nil, err
	}

	// The next couple of fields will contain the process file name enclosed by ()
	// so look for the last ) starting at the end
	i := 0
	for j := len(fields) - 1; j >= 0; j-- {
		if strings.HasSuffix(fields[j], ")") {
			i = j
			break
		}
	}
	if i < 1 {
		return nil, fmt.Errorf("could not find process name")
	}
	stat.Filename = fields[1]
	for j := 2; j <= i; j++ {
		stat.Filename = stat.Filename + " " + fields[j]
	}

	if (len(fields) - i) < 5 {
		return nil, MalformedStatErr
	}

	// the next field is the process state flag
	i++
	stat.State = fields[i]

	// the remaining fields are integers
	i++
	if err := parseInt(fields[i], &stat.Ppid); err != nil {
		return nil, MalformedStatErr
	}
	i++
	if err := parseInt(fields[i], &stat.Pgrp); err != nil {
		return nil, MalformedStatErr
	}
	i++
	if err := parseInt(fields[i], &stat.Session); err != nil {
		return nil, MalformedStatErr
	}
	return &stat, nil
}
440784
func ReadPidFile(name string) (pid int, err error) {
	var file *os.File
	if file, err = os.OpenFile(name, os.O_RDONLY, 0640); err != nil {
		return
	}
	defer file.Close()

	lock := &LockFile{file}
	pid, err = lock.ReadPid()
	return
}
93611
func ProcessInfo(pid int32) []string {
	userdata := []string{}

	p, err := process.NewProcess(pid)
	if err != nil {
		return userdata
	}

	uids, err := p.Uids()
	if err != nil {
		return userdata
	}

	groups, err := p.Gids()
	if err != nil {
		return userdata
	}

	username, err := p.Username()
	if err != nil {
		return userdata
	}

	for _, uid := range uids {
		userdata = append(userdata, "uid:"+strconv.Itoa(int(uid)))
	}

	for _, gid := range groups {
		userdata = append(userdata, "gid:"+strconv.Itoa(int(gid)))
	}

	userdata = append(userdata, "username:"+username)

	userid, err := user.Lookup(username)
	if err != nil {
		return userdata
	}

	gids, err := userid.GroupIds()
	if err != nil {
		return userdata
	}

	for i := 0; i < len(gids); i++ {
		userdata = append(userdata, "gids:"+gids[i])
		group, err := user.LookupGroupId(gids[i])
		if err != nil {
			continue
		}
		userdata = append(userdata, "groups:"+group.Name)
	}

	return userdata
}
600214
func WritePid(pid int, filename string) error {
	// write pid file as specified in
	// Documentation/devel/stage1-implementors-guide.md
	out, err := os.Getwd()
	if err != nil {
		return errwrap.Wrap(errors.New("cannot get current working directory"), err)
	}
	err = ioutil.WriteFile(filepath.Join(out, filename),
		[]byte(fmt.Sprintf("%d\n", pid)), 0644)
	if err != nil {
		return errwrap.Wrap(errors.New("cannot write pid file"), err)
	}
	return nil
}
287703
func (s *service) Pids(ctx context.Context, r *taskAPI.PidsRequest) (*taskAPI.PidsResponse, error) {
	log.G(ctx).Debugf("Pids: %s", r.ID)

	return nil, errdefs.ErrNotImplemented
}
645057
func (container *container) OpenProcess(pid int) (Process, error) {
	p, err := container.system.OpenProcess(pid)
	if err != nil {
		return nil, convertSystemError(err, container)
	}
	return &process{p: p}, nil
}