Home > front end >  Inexplicably different results between using os/exec and executing at the command line
Inexplicably different results between using os/exec and executing at the command line

Time:01-16

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?

CodePudding user response:

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.

  • Related