Golang查找指定进程实战指南
Golang查找指定进程实战指南
以下是一个简单的Golang示例程序,演示如何查找指定进程:gopackage main
import ( 'fmt' 'os' 'strconv' 'strings' 'os/exec')
func main() { if len(os.Args) < 2 { fmt.Println('Usage: ./find_process <process_name>') os.Exit(1) }
processName := os.Args[1]
output, err := execCommand('ps', '-A') if err != nil { fmt.Println(err) os.Exit(1) }
lines := strings.Split(output, '
') for _, line := range lines { if strings.Contains(line, processName) { fields := strings.Fields(line) pid, err := strconv.Atoi(fields[0]) if err != nil { continue } fmt.Printf('Process %s found with PID %d ', processName, pid) } }}
func execCommand(command string, args ...string) (string, error) { cmd := exec.Command(command, args...) output, err := cmd.Output() if err != nil { return '', err } return string(output), nil}
代码解读
- 接收参数: 程序接收一个命令行参数,即要查找的进程名称。2. 执行命令: 使用
exec.Command函数执行ps -A命令获取所有进程列表。3. 解析输出: 将命令输出按行分割,遍历每一行查找目标进程名。4. 输出结果: 若找到匹配进程,则解析出进程ID并打印。
函数说明
execCommand 函数用于执行外部命令并返回输出结果:
- 参数:命令名称和参数列表。* 返回值:命令输出字符串和错误信息。
总结
本示例展示了如何使用 Golang 查找指定进程,涉及命令行参数解析、系统命令执行和输出解析等实用技巧,希望能帮助你更好地进行 Golang 系统编程。
原文地址: https://www.cveoy.top/t/topic/fWGc 著作权归作者所有。请勿转载和采集!