gitee.com/h79/goutils@v1.22.10/common/system/process.go (about) 1 package system 2 3 import "errors" 4 5 // Process is the generic interface that is implemented on every platform 6 // and provides common operations for processes. 7 type Process interface { 8 // Pid is the process ID for this process. 9 Pid() int32 10 11 // PPid is the parent process ID for this process. 12 PPid() int32 13 14 // Name name running this process. This is not a path to the 15 Name() string 16 17 Path() string 18 } 19 20 // Processes returns all processes. 21 // 22 // This of course will be a point-in-time snapshot of when this method was 23 // called. Some operating systems don't provide snapshot capability of the 24 // process table, in which case the process table returned might contain 25 // ephemeral entities that happened to be running when this was called. 26 func Processes() ([]Process, error) { 27 return getProcesses() 28 } 29 30 // FindProcessByPId looks up a single process by pid. 31 // 32 // Process will be nil and error will be nil if a matching process is 33 // not found. 34 func FindProcessByPId(pid int32) (Process, error) { 35 ps, err := getProcesses() 36 if err != nil { 37 return nil, err 38 } 39 40 for _, p := range ps { 41 if p.Pid() == pid { 42 return p, nil 43 } 44 } 45 46 return nil, errors.New("process not found") 47 } 48 49 // FindProcessByName looks up a single process by pid. 50 // 51 // Process will be nil and error will be nil if a matching process is 52 // not found. 53 func FindProcessByName(name string) (Process, error) { 54 ps, err := getProcesses() 55 if err != nil { 56 return nil, err 57 } 58 59 for _, p := range ps { 60 if p.Name() == name { 61 return p, nil 62 } 63 } 64 return nil, errors.New("process not found") 65 }