Is there a go command equivalent to ps?

2019-08-20 17:26发布

问题:

I want a way to iterate through a list of PIDs scanning for processes with a particular command. For example the columns of ps ax are

 PID TTY      STAT   TIME COMMAND

I was wondering if there was a way for me to determine the COMMAND column of a PID given its number.

回答1:

The Go language and the ps command are unrelated.

The ps command is part of POSIX specification, and available on all Unix-like systems (including Linux, Solaris, *BSD, ....). Read ps(1). It is related to your operating system (and you probably don't have it on Windows). Read Operating Systems: Three Easy Pieces to learn more about OSes, and some Linux programming book like ALP to learn more about Linux programming. See also intro(2) & syscalls(2) (and find the Go equivalent of them).

I want a way to iterate through a list of PIDs scanning for processes with a particular command.

I was wondering if there was a way for me to determine the COMMAND column of a PID given its number.

This is unrelated to Go. You could use the /proc/ pseudo file system, see proc(5), which exists on all Linux systems, both with and without Go installed on them. /proc/ is internally used by ps(1), top(1), pmap(1), etc...

To iterate on the list of processes (on Linux), you need to read the /proc/ directory for numerical entries (e.g. /proc/1234/ exists if there is a process of pid 1234). To read a directory, use opendir(3), readdir(3), closedir(3), stat(2) in C and they all have their Go equivalent e.g. in ioutils package.

In particular, for process 1234, you could read /proc/1234/cmdline (which contains NUL byte separated strings). Of course you could read that file from some Go program. Try the od -cx /proc/self/cmdline command (using od(1)) to understand the format of that file ...

Pseudofiles in /proc/ are "pipe-like", have an apparent size (as given by stat(2) or by ls(1)...) of 0, and should be read sequentially, see this.



回答2:

go-ps may be useful for you if you want to do it in a portable way.



标签: linux go