Home >Backend Development >Golang >Why Does My Go Code Fail to Execute the `top` Command with Certain Arguments While the Same Command Works from the Console?
Calling Command with Some Arguments Works but Not with Others Despite Success from Console
This code snippet outputs details of 10 processes using the command /usr/bin/top with the arguments -n 10 and -l 2:
package main import ( "os/exec" ) func main() { print(top()) } func top() string { app := "/usr/bin/top" cmd := exec.Command(app, "-n 10", "-l 2") out, err := cmd.CombinedOutput() if err != nil { return err.Error() + " " + string(out) } value := string(out) return value }
However, adding the -o cpu argument (e.g., cmd := exec.Command(app, "-o cpu", "-n 10", "-l 2")) results in the error:
exit status 1 invalid argument -o: cpu /usr/bin/top usage: /usr/bin/top [-a | -d | -e | -c <mode>] [-F | -f] [-h] [-i <interval>] [-l <samples>] [-ncols <columns>] [-o <key>] [-O <secondaryKey>] [-R | -r] [-S] [-s <delay>] [-n <nprocs>] [-stats <key(s)>] [-pid <processid>] [-user <username>] [-U <username>] [-u]
Interestingly, the command top -o cpu -n 10 -l 2 works fine from the console in OS X 10.9.3.
The issue arises from the way arguments are separated in the Go code. The following line:
cmd := exec.Command(app, "-o cpu", "-n 10", "-l 2")
is equivalent to using the command top "-o cpu" "-n 10" "-l 2" in a shell. Most commands strictly parse arguments in this format. Therefore, top splits off the -o cpu as the first option, leaving the rest as its argument. This works for numerical arguments but fails when looking for a field named " cpu", causing the error.
To resolve this problem, separate the arguments as follows:
cmd := exec.Command(app, "-o", "cpu", "-n", "10", "-l", "2")
The above is the detailed content of Why Does My Go Code Fail to Execute the `top` Command with Certain Arguments While the Same Command Works from the Console?. For more information, please follow other related articles on the PHP Chinese website!