Created
April 12, 2018 12:26
-
-
Save jhinrichsen/a08c54d1dd32a7e3aba66c590ec4df66 to your computer and use it in GitHub Desktop.
Linux: report number of processes and threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This package is Linux only | |
package main | |
import ( | |
"flag" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"strconv" | |
"time" | |
) | |
func die(err error) { | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
// list all numerical files in dir. | |
func list(dir string) ([]int, error) { | |
var ids []int | |
fis, err := ioutil.ReadDir(dir) | |
if err != nil { | |
return ids, err | |
} | |
for _, fi := range fis { | |
i, err := strconv.Atoi(fi.Name()) | |
if err == nil { | |
ids = append(ids, i) | |
} | |
} | |
return ids, nil | |
} | |
// Pids returns all active processes identified by their process ID. | |
// Note that this is a volatile snapshot and may change as processes start | |
// and stop at any time. | |
func Pids() ([]int, error) { | |
return list("/proc") | |
} | |
// Tids returns all thread IDs for a given PID. | |
// TID is not as common as PID but serves a thread id nicely | |
func Tids(pid int) ([]int, error) { | |
return list(fmt.Sprintf("/proc/%d/task", pid)) | |
} | |
func main() { | |
var list = flag.Bool("list", false, "List all PIDs and their TIDs") | |
var total = flag.Bool("total", true, "Show totals") | |
flag.Parse() | |
pids, err := Pids() | |
die(err) | |
ntids := 0 | |
t := time.Now().Format(time.RFC3339) | |
for _, pid := range pids { | |
tids, err := Tids(pid) | |
die(err) | |
ntids += len(tids) | |
if *list { | |
fmt.Printf("%s\t%d\t%d\n", t, pid, len(tids)) | |
} | |
} | |
if *total { | |
fmt.Printf("%s\ttotal:\tPIDs:\t%d\tTIDs:\t%d\n", | |
t, len(pids), ntids) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment