I have maintained a list of pids of processes currently running on my system(Linux) from this now it would be great if i can get the process details from this pid i have come over syscall.Getrusage() in golang but i am not getting desired results. Does anyone have idea related to it
You could look at /proc/[pid]/stat
. For example, using Go 1,
package main
import (
"fmt"
"io/ioutil"
"os"
"strconv"
)
func Pids() ([]int, error) {
f, err := os.Open(`/proc`)
if err != nil {
return nil, err
}
defer f.Close()
names, err := f.Readdirnames(-1)
if err != nil {
return nil, err
}
pids := make([]int, 0, len(names))
for _, name := range names {
if pid, err := strconv.ParseInt(name, 10, 0); err == nil {
pids = append(pids, int(pid))
}
}
return pids, nil
}
func ProcPidStat(pid int) ([]byte, error) {
// /proc/[pid]/stat
// https://www.kernel.org/doc/man-pages/online/pages/man5/proc.5.html
filename := `/proc/` + strconv.FormatInt(int64(pid), 10) + `/stat`
return ioutil.ReadFile(filename)
}
func main() {
pids, err := Pids()
if err != nil {
fmt.Println("pids:", err)
return
}
if len(pids) > 0 {
pid := pids[0]
stat, err := ProcPidStat(pid)
if err != nil {
fmt.Println("pid:", pid, err)
return
}
fmt.Println(`/proc/[pid]/stat:`, string(stat))
}
}
Output:
/proc/[pid]/stat: 1 (init) S 0 1 1 0 -1 4202752 11119 405425 21 57 78 92 6643 527 20 0 1 0 3 24768512 563 184467440737095
This might not be exactly what the asker wanted (there's not much clear info on what type of details are required for each process id), but you can get some details of a task by its pid using the BASH command ps -p $PID
(ps being short for process status)
With default options as ps -p $PID
this returns:
java
)More information about this process id can be shown using the -o options flag. For a list, see this documentation page.
Here's one example that tells you a particular process PID's full command with arguments, user, group and memory usage (note how the multiple -o flags each take a pair, and how the command outputs with lots of whitespace padding):
ps -p $PID -o pid,vsz=MEMORY -o user,group=GROUP -o comm,args=ARGS
Tip: for human-read output in the console, make args the last option - it'll usually be the longest and might get cut short otherwise.
ps -p PID -o comm=
Enter the code above where PID is PID of the process.
Just type this and you will get what you want, replace 'type_pid_here' with pid.
cat /proc/type_pid_here/status