这里主要分享go中获取机器进程和进程参数的一些代码
获取当前机器所有的pid:
import "github.com/shirou/gopsutil/process"
pids, err := process.Pids()
for _, pid := range pids {
proc, err := process.NewProcess(pid)
if err != nil {
log.Errorf("get pid %d info error: %s", pid, err.Error())
continue
}
// 获取进程命令行参数
cmdLine, err := proc.Cmdline()
if err != nil {
log.Errorf("get cmdLine of pid %d error: %s", pid, err.Error())
continue
}
log.Infof("cmdline of pid %d is: %s", pid, cmdLine)
if !strings.Contains(cmdLine, "java") {
continue
}
//获取jmx端口:
// 检查命令行参数是否包含"java"和"Dcom.sun.management.jmxremote.port"
var jmxPort string
if strings.Contains(cmdLine, "Dcom.sun.management.jmxremote.port") {
// 提取JMX端口
re := regexp.MustCompile(`Dcom.sun.management.jmxremote.port=(\d+)`)
match := re.FindStringSubmatch(cmdLine)
if len(match) > 1 {
jmxPort = match[1]
log.Infof("PID: %v, JMX Port: %v , %s, cmdLine: %s\n", pid, match[1], jmxPort, cmdLine)
} else {
log.Infof("not found jmxremote.port or jmxremote.rmi.port")
log.Infof("PID: %v, of cmdLine: %s, has no Dcom.sun.management.jmxremote.port \n", pid, cmdLine)
}
}
Process.CmdlineWithContext 方法的实现依赖于 callPsWithContext 函数来获取进程的命令行参数。这个方法的实现如下:
func (