Process management
Go is not that good at dealing with processes and process management in general. Nevertheless, this section will present a small Go program that lists all the processes of a Unix machine by executing a Unix command and getting its output. The name of the program will be listProcess.go
. It works on both Linux and macOS systems, and will be presented in three parts.
The first part of the program is the following:
package main import ( "fmt" "os" "os/exec" "syscall" )
The second part of listProcess.go
has the following Go code:
func main() { PS, err := exec.LookPath("ps") if err != nil { fmt.Println(err) } fmt.Println(PS) command := []string{"ps", "-a", "-x"} env := os.Environ() err = syscall.Exec(PS, command, env)
As you can see, you first need to get the path of the executable file using exec.LookPath()
to make sure that you are not going to accidentally execute another binary file and then define the command you want...