// TerminateAllWithProcessesFn stops processes processesFn that satify the matchFn.
// It returns the pids that were terminated.
// This method only logs errors, if you need error handling, you can should use a different implementation.
486736
func TerminateAllWithProcessesFn(fn processesFn, matchFn MatchFn, killDelay time.Duration, log Log) (pids []int) {
	pids, err := findPIDsWithFn(fn, matchFn, log)
	if err != nil {
		log.Errorf("Error finding process: %s", err)
		return
	}
	if len(pids) == 0 {
		return
	}
	for _, pid := range pids {
		if err := TerminatePID(pid, killDelay, log); err != nil {
			log.Errorf("Error terminating %d: %s", pid, err)
		}
	}
	return
}
22400
func (b *bufferedBackend) Shutdown() {
	// Wait until the routine spawned in Run method exits.
	<-b.shutdownCh

	// Wait until all sending routines exit.
	//
	// - When b.shutdownCh is closed, we know that the goroutine in Run has terminated.
	// - This means that processIncomingEvents has terminated.
	// - Which means that b.buffer is closed and cannot accept any new events anymore.
	// - Because processEvents is called synchronously from the Run goroutine, the waitgroup has its final value.
	// Hence wg.Wait will not miss any more outgoing batches.
	b.wg.Wait()

	b.delegateBackend.Shutdown()
}
1273285
func (v *Validator) CheckProcess() (errs error) {
	logrus.Debugf("check process")

	if v.spec.Process == nil {
		return
	}

	process := v.spec.Process
	if !osFilepath.IsAbs(v.platform, process.Cwd) {
		errs = multierror.Append(errs,
			specerror.NewError(
				specerror.ProcCwdAbs,
				fmt.Errorf("cwd %q is not an absolute path", process.Cwd),
				rspec.Version))
	}

	for _, env := range process.Env {
		if !envValid(env) {
			errs = multierror.Append(errs, fmt.Errorf("env %q should be in the form of 'key=value'. The left hand side must consist solely of letters, digits, and underscores '_'", env))
		}
	}

	if len(process.Args) == 0 {
		errs = multierror.Append(errs,
			specerror.NewError(
				specerror.ProcArgsOneEntryRequired,
				fmt.Errorf("args must not be empty"),
				rspec.Version))
	} else {
		if filepath.IsAbs(process.Args[0]) && v.spec.Root != nil {
			var rootfsPath string
			if filepath.IsAbs(v.spec.Root.Path) {
				rootfsPath = v.spec.Root.Path
			} else {
				rootfsPath = filepath.Join(v.bundlePath, v.spec.Root.Path)
			}
			absPath := filepath.Join(rootfsPath, process.Args[0])
			fileinfo, err := os.Stat(absPath)
			if os.IsNotExist(err) {
				logrus.Warnf("executable %q is not available in rootfs currently", process.Args[0])
			} else if err != nil {
				errs = multierror.Append(errs, err)
			} else {
				m := fileinfo.Mode()
				if m.IsDir() || m&0111 == 0 {
					errs = multierror.Append(errs, fmt.Errorf("arg %q is not executable", process.Args[0]))
				}
			}
		}
	}

	if v.platform == "linux" || v.platform == "solaris" {
		errs = multierror.Append(errs, v.CheckRlimits())
	}

	if v.platform == "linux" {
		if v.spec.Process.Capabilities != nil {
			errs = multierror.Append(errs, v.CheckCapabilities())
		}

		if len(process.ApparmorProfile) > 0 {
			profilePath := filepath.Join(v.bundlePath, v.spec.Root.Path, "/etc/apparmor.d", process.ApparmorProfile)
			_, err := os.Stat(profilePath)
			if err != nil {
				errs = multierror.Append(errs, err)
			}
		}
	}

	return
}
480910
func (dbp *Process) kill() (err error) {
	if dbp.exited {
		return nil
	}
	if !dbp.threads[dbp.pid].Stopped() {
		return errors.New("process must be stopped in order to kill it")
	}
	if err = sys.Kill(-dbp.pid, sys.SIGKILL); err != nil {
		return errors.New("could not deliver signal " + err.Error())
	}
	if _, _, err = dbp.wait(dbp.pid, 0); err != nil {
		return
	}
	dbp.postExit()
	return
}
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
}
1006308
func TerminateApp(context Context, log Log) error {
	appExecName := "Keybase"
	logf := logger.NewLoggerf(log)
	log.Info("Stopping Keybase app")
	appPIDs := process.TerminateAll(process.NewMatcher(appExecName, process.ExecutableEqual, logf), 5*time.Second, logf)
	if len(appPIDs) > 0 {
		log.Info("Terminated %s %v", appExecName, appPIDs)
	}
	return nil
}
472794
func (iop ioPipe) closeProc() error {
	result := make(chan error, 1)
	go func() { _, err := iop.proc.Wait(); result <- err }()
	if err := iop.proc.Signal(os.Interrupt); err != nil {
		return err
	}
	select {
	case err := <-result:
		return err
	case <-time.After(procTimeout):
		if err := iop.proc.Kill(); err != nil {
			return fmt.Errorf("error killing process after timeout: %s", err)
		}
		return errProcStopTimeout
	}
}
722921
func (process *Process) Kill() (_ bool, err error) {
	process.handleLock.RLock()
	defer process.handleLock.RUnlock()

	operation := "hcsshim::Process::Kill"
	process.logOperationBegin(operation)
	defer func() { process.logOperationEnd(operation, err) }()

	if process.handle == 0 {
		return false, makeProcessError(process, operation, ErrAlreadyClosed, nil)
	}

	var resultp *uint16
	syscallWatcher(process.logctx, func() {
		err = hcsTerminateProcess(process.handle, &resultp)
	})
	events := processHcsResult(resultp)
	delivered, err := process.processSignalResult(err)
	if err != nil {
		err = makeProcessError(process, operation, err, events)
	}
	return delivered, err
}
271893
func (c *Container) ExecdProcesses() (o []rproc.Process) {
	c.mu.Lock()
	defer c.mu.Unlock()
	for _, p := range c.processes {
		o = append(o, p)
	}
	return o
}
23352
func (m *ProcessManager) ListProcesses(pids []int64) []byte {
	w := new(bytes.Buffer)

	m.mu.Lock()

	if len(pids) == 0 {
		for _, p := range m.entries {
			_, _ = w.WriteString(p.toXML())
		}
	} else {
		for _, id := range pids {
			p, ok := m.entries[id]
			if !ok {
				continue
			}

			_, _ = w.WriteString(p.toXML())
		}
	}

	m.mu.Unlock()

	return w.Bytes()
}
1230019
func (e *UniversalExecutor) cleanupChildProcesses(proc *os.Process) error {
	// We must first verify if the process is still running.
	// (Windows process often lingered around after being reported as killed).
	handle, err := syscall.OpenProcess(syscall.PROCESS_TERMINATE|syscall.SYNCHRONIZE|syscall.PROCESS_QUERY_INFORMATION, false, uint32(proc.Pid))
	if err != nil {
		return os.NewSyscallError("OpenProcess", err)
	}
	defer syscall.CloseHandle(handle)

	result, err := syscall.WaitForSingleObject(syscall.Handle(handle), 0)

	switch result {
	case syscall.WAIT_OBJECT_0:
		return nil
	case syscall.WAIT_TIMEOUT:
		// Process still running.  Just kill it.
		return proc.Kill()
	default:
		return os.NewSyscallError("WaitForSingleObject", err)
	}
}
792114
func (l *loop) terminate(err error) {
	l.mux.Lock()
	defer l.mux.Unlock()
	if l.err == nil {
		l.err = err
	}
	if l.status != Running {
		return
	}
	l.status = Stopping
	select {
	case <-l.stopC:
	default:
		close(l.stopC)
	}
}
1171144
func (p *setnsProcess) terminate() error {
	if p.cmd.Process == nil {
		return nil
	}
	err := p.cmd.Process.Kill()
	if _, werr := p.wait(); err == nil {
		err = werr
	}
	return err
}
616017
func (m *podContainerManagerImpl) killOnePid(pid int) error {
	// os.FindProcess never returns an error on POSIX
	// https://go-review.googlesource.com/c/go/+/19093
	p, _ := os.FindProcess(pid)
	if err := p.Kill(); err != nil {
		// If the process already exited, that's fine.
		if strings.Contains(err.Error(), "process already finished") {
			// Hate parsing strings, but
			// vendor/github.com/opencontainers/runc/libcontainer/
			// also does this.
			klog.V(3).Infof("process with pid %v no longer exists", pid)
			return nil
		}
		return err
	}
	return nil
}
496575
func (p *Process) deleteProcess() error {
	if p.command == nil || p.command.Process == nil {
		return nil
	}

	// Close the process watcher
	if p.cancelChan != nil {
		close(p.cancelChan)
	}

	p.log.Debugf("Process %s deleted", p.name)
	return nil
}
835853
func KillAll(matcher Matcher, log Log) (pids []int) {
	pids, err := findPIDsWithFn(ps.Processes, matcher.Fn(), log)
	if err != nil {
		log.Errorf("Error finding process: %s", err)
		return
	}
	if len(pids) == 0 {
		return
	}
	for _, pid := range pids {
		if err := KillPID(pid, log); err != nil {
			log.Errorf("Error killing %d: %s", pid, err)
		}
	}
	return
}
374238
func (p *Process) Stop() error {
	p.mtx.Lock()
	defer p.mtx.Unlock()

	if !p.running {
		return ErrStopped
	}
	return p.stop()
}