Home  >  Article  >  Backend Development  >  Golang no output when I try to execute command

Golang no output when I try to execute command

PHPz
PHPzforward
2024-02-12 16:12:191056browse

Golang 当我尝试执行命令时没有输出

Question content

I try to execute some commands (within config.json) Only the npm command has display output

This is my first time using stackoverflow Please forgive me if I didn’t do well

expected outcome: When I write any command in config.json Will output the correct result

main.go

func main () {
    file, _ := os.open("config.json")
    byteres, _ := ioutil.readall(file)
    var config config
    json.unmarshal(byteres, &config)
    defer file.close()

    process := exec.command(config.startcommand)
    stdout, _ := process.stdoutpipe()
    processscanner := bufio.newscanner(stdout)
    processscanner.split(bufio.scanlines)

    process.start()
    go func() {
        for processscanner.scan() {
            message := processscanner.text()
            fmt.println(message)
        }
    }()
}

Configuration.json

{
    "StartCommand": "npm"
}

Solution

Your main function will not wait for your goroutine to complete. Use sync.WaitGroup to block main until the goroutine completes.

The above is the detailed content of Golang no output when I try to execute command. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete