I am working on a plugin that can count the processes running on a Linux system. I have searched around and it seems that I need to access /proc and gather information from there. I also tried using the os, os/exec, and syscall packages to run the external command ps -A --no-headers | wc -l
but this isn't working either. I am coding this in golang as well. Any help or suggestions are welcome.
2 Answers
You can find the code that the Linux ps
uses to iterate through the list of processes here:
https://gitlab.com/procps-ng/procps/blob/master/proc/readproc.c#L1167
In short, the algorithm is:
opendir
on/proc
- call
readdir
until an entry whose first character is a digit is returned.
So to count the number of processes, you can read through the entire directory and count how many entries match.
You can do this in Go using os.Open
to open /proc
, and then call the Readdirnames
method to list the processes.
The following program works for me:
package main
import (
"fmt"
"log"
"os/exec"
)
func main() {
out, err := exec.Command("/bin/sh", "-c", "ps -A --no-headers | wc -l").Output()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Number of running processes: %s\n", out)
}
Note that you have to use /bin/sh -c
. exec.Command
executes a single program (an executable file), such as /bin/sh
or ps
or tail
.
When you type ps -A --no-headers | wc -l
in your command prompt this expression is interpreted by a shell program (such as /bin/sh
) and the shell program launches two programs (ps
and wc
) and pipes (|
) the output of the first program to the input of the second program.
/bin/sh -c command
is equivalent to typing command
in a terminal (with some minor differences, read man sh
for more details).
-
This is very similar to my code but how can you go about testing this to make sure it's working? Sorry if this isn't the right question. I'm very new to Golang. Jan 12, 2016 at 6:15
-
I am not sure I understand your question. When I compile this code and run the resulting application I see reasonable output. This code will not work on Windows or on play.golang.org. Probably you should start by reading golang.org/doc/install– kostyaJan 12, 2016 at 6:41
-
When I run that program it prints out [50 48 53 10]. I ran
ps -A --no-headers | wc -l
right after this and saw that I have 205 processes running. If I'm reading the documentation correctly, the numbers your program is printing out are bytes. How do these numbers relate? Jan 13, 2016 at 0:23 -
what version of Go are you using? Try changing
fmt.Printf("Number of running processes: %s\n", out)
tofmt.Printf("Number of running processes: %s\n", string(out))
– kostyaJan 13, 2016 at 2:29 -
That worked. I am using
go version go1.4
. New question for you: why did theexec.Command("/bin/sh", "-c"
need the/bin/sh -c
part? I had the same for the rest of the command but it didn't work until I added in the part you had. Jan 14, 2016 at 5:15
/proc/
directory and count the numerical subdirectories there (like/proc/1234
)