github.com/nya3jp/tast@v0.0.0-20230601000426-85c8e4d83a9b/src/go.chromium.org/tast/core/internal/runner/bundles.go (about)

     1  // Copyright 2018 The ChromiumOS Authors
     2  // Use of this source code is governed by a BSD-style license that can be
     3  // found in the LICENSE file.
     4  
     5  package runner
     6  
     7  import (
     8  	"github.com/shirou/gopsutil/v3/process"
     9  	"golang.org/x/sys/unix"
    10  )
    11  
    12  // killSession makes a best-effort attempt to kill all processes in session sid.
    13  // It makes several passes over the list of running processes, sending sig to any
    14  // that are part of the session. After it doesn't find any new processes, it returns.
    15  // Note that this is racy: it's possible (but hopefully unlikely) that continually-forking
    16  // processes could spawn children that don't get killed.
    17  func killSession(sid int, sig unix.Signal) {
    18  	const maxPasses = 3
    19  	for i := 0; i < maxPasses; i++ {
    20  		pids, err := process.Pids()
    21  		if err != nil {
    22  			return
    23  		}
    24  		n := 0
    25  		for _, pid := range pids {
    26  			pid := int(pid)
    27  			if s, err := unix.Getsid(pid); err == nil && s == sid {
    28  				unix.Kill(pid, sig)
    29  				n++
    30  			}
    31  		}
    32  		// If we didn't find any processes in the session, we're done.
    33  		if n == 0 {
    34  			return
    35  		}
    36  	}
    37  }