php editor Zimo brings you an analysis of the puzzlingly different results that occur when using the os/exec function in PHP and executing commands on the command line. In practical applications, we may encounter a situation where a command that can be successfully executed on the command line cannot obtain the same result when using the os/exec function. This situation often leaves us confused and difficult to find a solution to. This article will analyze the reasons for you and provide solutions to help you better understand and apply the os/exec function.
I wrote a program to run commands in golang using package os/exec
.
import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("taskkill", "/f /im VInTGui.exe") err := cmd.Run() if err != nil { fmt.Printf("err: %v\n", err) } }
When I run the program, it prints: err: exit status 1
But when I run the command taskkill /f /im vintgui.exe
in windows command line. It worked.
Why do running commands through the os/exec
package have different results than running commands directly through the windows command line
(using the same user and the same permissions)? How can I fix my program?
The solution is to use the stderr
property of the command
object. This can be done like this:
cmd := exec.command("taskkill", "/f /im vintgui.exe") var out bytes.buffer var stderr bytes.buffer cmd.stdout = &out cmd.stderr = &stderr err := cmd.run() if err != nil { fmt.printf("%v: %s\n", err, stderr.string()) return } fmt.println("result: " + out.string())
According to your situation, just change
exec.command("taskkill", "/f /im vintgui.exe")
to
exec.Command("taskkill", "/f", "/im", "VInTGui.exe")
Do not combine all parameters into one string.
The above is the detailed content of Puzzlingly different results between using os/exec and executing from the command line. For more information, please follow other related articles on the PHP Chinese website!