简体   繁体   中英

Inexplicably different results between using os/exec and executing at the command line

I write a program which run a command use package os/exec in Golang.

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 that program, it printed: err: exit status 1

But when I run command taskkill /f /im VInTGui.exe in Windows Command Line. It success.

Why run command by package os/exec and run command directly by Windows Command Line (using same user same permissions) has Different result? 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())

In your case, just change

exec.Command("taskkill", "/f /im VInTGui.exe")

to

exec.Command("taskkill", "/f", "/im",  "VInTGui.exe")

Don't merge all arguments to one string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM