可以使用 ps
命令结合 grep
命令来获取指定进程的全路径:
ps -p <pid> -o comm=
其中,<pid>
是要查询的进程的 PID。上述命令会返回该进程的命令名称,然后再使用 which
命令获取命令所在位置即可得到该进程的全路径。例如:
which $(ps -p 12345 -o comm=)
其中,12345
是要查询的进程的 PID。
在 Golang 中,可以使用 os.Getpid()
函数获取当前进程的 PID。然后再通过执行上述命令来获取进程全路径。完整代码如下:
package main
import (
"fmt"
"os"
"os/exec"
)
func main() {
pid := os.Getpid()
cmd := exec.Command("sh", "-c", fmt.Sprintf("which $(ps -p %d -o comm=)", pid))
output, err := cmd.Output()
if err != nil {
fmt.Println(err)
return
}
fullPath := string(output)
fmt.Printf("Process full path: %s\n", fullPath)
}
注意,需要先安装 grep
命令才能使用上述命令。