dbtester/vendor/github.com/gyuho/linux-inspect/psn/util_proc_linux.go

81 lines
1.6 KiB
Go

package psn
import (
"fmt"
"io/ioutil"
"path/filepath"
"strconv"
"strings"
)
func convertProcStatus(s string) string {
ns := strings.TrimSpace(s)
if len(s) > 1 {
ns = ns[:1]
}
switch ns {
case "D":
return "D (uninterruptible sleep)"
case "R":
return "R (running)"
case "S":
return "S (sleeping)"
case "T":
return "T (stopped by job control signal)"
case "t":
return "t (stopped by debugger during trace)"
case "Z":
return "Z (zombie)"
default:
return fmt.Sprintf("unknown process %q", s)
}
}
func pidFromFd(s string) (int64, error) {
// get 5261 from '/proc/5261/fd/69'
return strconv.ParseInt(strings.Split(s, "/")[2], 10, 64)
}
// ListPIDs reads all PIDs in '/proc'.
func ListPIDs() ([]int64, error) {
ds, err := ioutil.ReadDir("/proc")
if err != nil {
return nil, err
}
pids := make([]int64, 0, len(ds))
for _, f := range ds {
if f.IsDir() && isInt(f.Name()) {
id, err := strconv.ParseInt(f.Name(), 10, 64)
if err != nil {
return nil, err
}
pids = append(pids, id)
}
}
return pids, nil
}
// ListProcFds reads '/proc/*/fd/*' to grab process IDs.
func ListProcFds() ([]string, error) {
// returns the names of all files matching pattern
// or nil if there is no matching file
fs, err := filepath.Glob("/proc/[0-9]*/fd/[0-9]*")
if err != nil {
return nil, err
}
return fs, nil
}
// GetProgram returns the program name.
func GetProgram(pid int64) (string, error) {
// Readlink needs root permission
// return os.Readlink(fmt.Sprintf("/proc/%d/exe", pid))
rs, err := rawProcStatus(pid)
if err != nil {
return "", err
}
return rs.Name, nil
}