Home > Backend Development > Golang > Puzzlingly different results between using os/exec and executing from the command line

Puzzlingly different results between using os/exec and executing from the command line

王林
Release: 2024-02-14 12:45:09
forward
985 people have browsed it

使用 os/exec 和在命令行执行之间出现令人费解的不同结果

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.

Question content

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)
    }
}
Copy after login

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?

Solution

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())
Copy after login

According to your situation, just change

exec.command("taskkill", "/f /im vintgui.exe")
Copy after login

to

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

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template