// HandlerProcess returns the current process' PID.
559232
func HandlerProcess(_ *logrus.Entry, _ *CustomFormatter) (interface{}, error) {
	return os.Getpid(), nil
}
745352
func (p *Plugin) AttachProcess(name string, cmd string, pid int, options ...POption) (ProcessInstance, error) {
	pr, err := os.FindProcess(pid)
	if err != nil {
		return nil, errors.Errorf("cannot attach to process with PID %d: %v", pid, err)
	}
	attachedPr := &Process{
		log:        p.Log,
		name:       name,
		cmd:        cmd,
		options:    &POptions{},
		command:    &exec.Cmd{Process: pr},
		sh:         &status.Reader{Log: p.Log},
		cancelChan: make(chan struct{}),
	}
	for _, option := range options {
		option(attachedPr.options)
	}
	p.processes = append(p.processes, attachedPr)

	attachedPr.status, err = attachedPr.sh.ReadStatusFromPID(attachedPr.GetPid())
	if err != nil {
		p.Log.Warnf("failed to read process (PID %d) status: %v", pid, err)
	}

	go attachedPr.watch()

	if attachedPr.options.template {
		p.writeAsTemplate(attachedPr)
	}

	return attachedPr, nil
}
372113
func Handle(h Handler) {
	m := &manager{
		Reader:  os.Stdin,
		Writer:  os.Stdout,
		Handler: h,
	}

	m.Start()
}
519917
func (s *netCls) RemoveProcess(cgroupname string, pid int) error {

	_, err := os.Stat(filepath.Join(basePath, s.TriremePath, cgroupname))
	if os.IsNotExist(err) {
		return fmt.Errorf("cannot clean up process. cgroup does not exist: %s", err)
	}

	data, err := ioutil.ReadFile(filepath.Join(basePath, procs))
	if err != nil {
		return fmt.Errorf("cannot cleanup process: %s", err)
	}
	if !strings.Contains(string(data), strconv.Itoa(pid)) {
		return errors.New("cannot cleanup process. process is not a part of this cgroup")
	}

	if err := ioutil.WriteFile(filepath.Join(basePath, procs), []byte(strconv.Itoa(pid)), 0644); err != nil {
		return fmt.Errorf("cannot clean up process: %s", err)
	}

	return nil
}
703434
func (p *Process) waitOnProcess() (*os.ProcessState, error) {
	if p.command == nil || p.command.Process == nil {
		return &os.ProcessState{}, nil
	}

	return p.command.Process.Wait()
}
104101
func Pids() ([]int32, error) {
	var ret []int32
	pid, err := process.Pids()
	if err != nil {
		return ret, err
	}

	return pid, err
}
1186074
func (a *AppInstance) processCommand(url string, body string, method string) *CommandResponse {
	jsonMessage, err := json.Marshal(Command{URL: url, Method: method, Body: body})
	if err != nil {
		return &CommandResponse{}
	}

	a.commandChannel <- jsonMessage
	for {
		select {
		case r, r_ok := <-a.responseChannel:
			if r_ok {
				return r
			}
		case <-time.After(5 * time.Second):
			return &CommandResponse{}
		}
	}
}
1024932
func waitForProcess(ctx context.Context, process *process, p *os.Process, s *service) {
	pid := uint32(p.Pid)

	// Store the default non-exited value for calls to stat
	process.exit.Store(&processExit{
		pid:        pid,
		exitStatus: 255,
		exitedAt:   time.Time{},
		exitErr:    nil,
	})

	var status int
	processState, eerr := p.Wait()
	if eerr != nil {
		status = 255
		p.Kill()
	} else {
		status = processState.Sys().(syscall.WaitStatus).ExitStatus()
	}

	now := time.Now()
	process.exit.Store(&processExit{
		pid:        pid,
		exitStatus: uint32(status),
		exitedAt:   now,
		exitErr:    eerr,
	})

	// Wait for the relay
	process.relay.wait()

	// Wait for the started event to fire if it hasn't already
	process.startedWg.Wait()

	// We publish the exit before freeing upstream so that the exit event always
	// happens before any delete event.
	s.publisher.Publish(
		ctx,
		runtime.TaskExitEventTopic,
		&eventstypes.TaskExit{
			ContainerID: process.cid,
			ID:          process.id,
			Pid:         pid,
			ExitStatus:  uint32(status),
			ExitedAt:    now,
		})

	// close the client io, and free upstream waiters
	process.close()
}
228757
func (computeSystem *System) OpenProcess(pid int) (_ *Process, err error) {
	computeSystem.handleLock.RLock()
	defer computeSystem.handleLock.RUnlock()

	// Add PID for the context of this operation
	computeSystem.logctx[logfields.ProcessID] = pid
	defer delete(computeSystem.logctx, logfields.ProcessID)

	operation := "hcsshim::ComputeSystem::OpenProcess"
	computeSystem.logOperationBegin(operation)
	defer func() { computeSystem.logOperationEnd(operation, err) }()

	var (
		processHandle hcsProcess
		resultp       *uint16
	)

	if computeSystem.handle == 0 {
		return nil, makeSystemError(computeSystem, "OpenProcess", "", ErrAlreadyClosed, nil)
	}

	syscallWatcher(computeSystem.logctx, func() {
		err = hcsOpenProcess(computeSystem.handle, uint32(pid), &processHandle, &resultp)
	})
	events := processHcsResult(resultp)
	if err != nil {
		return nil, makeSystemError(computeSystem, "OpenProcess", "", err, events)
	}

	process := newProcess(processHandle, pid, computeSystem)
	if err = process.registerCallback(); err != nil {
		return nil, makeSystemError(computeSystem, "OpenProcess", "", err, nil)
	}
	go process.waitBackground()

	return process, nil
}
1372427
func (h *CommandHandler) HandleCommand(ctx context.Context, cmd eh.Command) error {
	h.handlersMu.RLock()
	defer h.handlersMu.RUnlock()

	if handler, ok := h.handlers[cmd.CommandType()]; ok {
		return handler.HandleCommand(ctx, cmd)
	}

	return ErrHandlerNotFound
}
104950
func NewProcess() *Process {
	return &Process{
		BinPath: DefaultBinPath,
		Port:    DefaultPort,
		Stdout:  os.Stdout,
		Stderr:  os.Stderr,
	}
}
645670
func (b *bufferedBackend) processEvents(events []*auditinternal.Event) {
	if len(events) == 0 {
		return
	}

	// TODO(audit): Should control the number of active goroutines
	// if one goroutine takes 5 seconds to finish, the number of goroutines can be 5 * defaultBatchThrottleQPS
	if b.throttle != nil {
		b.throttle.Accept()
	}

	if b.asyncDelegate {
		b.wg.Add(1)
		go func() {
			defer b.wg.Done()
			defer runtime.HandleCrash()

			// Execute the real processing in a goroutine to keep it from blocking.
			// This lets the batching routine continue draining the queue immediately.
			b.delegateBackend.ProcessEvents(events...)
		}()
	} else {
		func() {
			defer runtime.HandleCrash()

			// Execute the real processing in a goroutine to keep it from blocking.
			// This lets the batching routine continue draining the queue immediately.
			b.delegateBackend.ProcessEvents(events...)
		}()
	}
}
1349438
func FindProcess(pid int) (process *os.Process, err error) {
	process, err = findProcess(pid)
	if err != nil {
		_ = process.Release()
		process = nil
	}
	return process, err
}
1346237
func handler(name string, options *ProcessorOptions) (IntrinsicHandler, bool) {

	// Check if we have a handler for this intrinsic type in the instrinsic handler
	// overrides in the options provided to Process()
	if options != nil {
		if h, ok := options.IntrinsicHandlerOverrides[name]; ok {
			return h, true
		}
	}

	if h, ok := defaultIntrinsicHandlers[name]; ok {
		return h, true
	}

	return nil, false

}
873690
func process(c net.Conn, handler Function, timeout int) {

	defer c.Close()

	b4 := make([]byte, 4)

	log.Println("starting Server.process: connection accepted")

	for {

		// Each message has a 4 byte header, an integer indicating the length:
		//
		//    message = LEN(uint32) BYTES
		//
		// Thus, first read 4 bytes (LEN)

		c.SetReadDeadline(time.Now().Add(time.Second * time.Duration(timeout)))
		i, err := c.Read(b4)

		if i == 0 {
			break
		}

		if err != nil || i != 4 {
			log.Println("ogdlrf.Serve, error while trying to read LEN,", i, err)
			break
		}

		l := int(binary.BigEndian.Uint32(b4))
		log.Println("ogdlrf.Serve, rec LEN", l)
		if l == 0 {
			log.Println("LEN is 0, timeout was", timeout)
			break
		}

		// Read the body of the message

		buf := make([]byte, l)
		if buf == nil {
			log.Println("ogdlrf.Serve, cannot allocate memory for message")
			break
		}
		i, err = c.Read(buf)

		if err != nil {
			log.Println("ogdlrf.Serve, error reading message body, ", err)
			break
		}

		if i != l {
			log.Println("ogdlrf.Serve, error reading message body, LEN is", i, "should be", l)
			break
		}

		g := ogdl.FromBinary(buf)
		if g == nil || g.Out == nil {
			log.Println("ogdlrf.Serve, nothing in buf to produce a graph")
			break
		}
		r := handler(c, g)

		// Write message back
		buf = r.Binary()
		binary.BigEndian.PutUint32(b4, uint32(len(buf)))

		i, err = c.Write(b4)

		if i != 4 || err != nil {
			log.Println("ogdlrf.Serve, error writing LEN header", i, err)
			break
		}

		i, err = c.Write(buf)

		if err != nil {
			log.Println("ogdlrf.Serve, error writing body,", err)
			break
		}
		if i != len(buf) {
			log.Println("ogdlrf.Serve, error writing body, LEN is", i, "should be", len(buf))
			break
		}
		log.Println("ogdlrf.Serve, body LEN", len(buf))
	}
	log.Println("ending Server.process and closing connection")
}
478135
func (l *HostStateListener) PostProcess(p map[string]struct{}) {
	// We are running all of the containers we are supposed to, now
	// shut down any containers we are not supposed to be running
	l.mu.Lock()
	defer l.mu.Unlock()
	stateIDs := l.getExistingThreadStateIDs()
	var orphanedStates []string
	for _, s := range stateIDs {
		if _, ok := p[s]; !ok {
			orphanedStates = append(orphanedStates, s)
			plog.WithField("stateid", s).Info("Detected orphaned container")
		}
	}

	if len(orphanedStates) > 0 {
		l.cleanUpContainers(orphanedStates, false)
		plog.WithField("count", len(orphanedStates)).Info("Cleaned up all orphaned containers")
	}
}
604075
func TraceHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		pprof.Trace(ctx.Writer, ctx.Request)
	}
}