登录
首页 >  Golang >  Go教程

GoLang exec.Command() 后台守护不执行 Shell 命令:如何解决?

时间:2024-12-22 12:19:08 322浏览 收藏

欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《GoLang exec.Command() 后台守护不执行 Shell 命令:如何解决?》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!

GoLang exec.Command() 后台守护不执行 Shell 命令:如何解决?

golang exec.command 后台守护不执行 shell 问题

在使用 golang 的 exec.command() 命令在后台守护进程时,遇到程序运行但不执行 shell 命令的情况。以下是可能的原因和解决方案:

原因:exec.command() 的阻塞行为

cmd.run() 会阻塞当前 goroutine,直到命令执行完毕。然而,在后台守护模式下,由于主进程继续运行,cmd.run() 可能不会等到 shell 命令完成。

解决方案:使用 stdoutpipe() 获取 shell 输出

为了解决这个问题,可以使用 stdoutpipe() 获取 shell 命令输出的管道。这样,你可以从管道中读取输出,而不必等到命令执行完毕。

output := exec.command("ls")
stdout, err := output.stdoutpipe()
_ = err // todo: handle error

supervisord 设置

在使用 supervisord 进行后台守护时,请确保 supervisord 配置正确地将输出管道连接到期望的日志文件中。

其他注意事项

  • 确保 shell 命令具有正确的执行权限。
  • 检查程序的工作目录是否正确。
  • 根据 shell 命令的退出代码检查错误(使用 stdoutpipe() 获取的管道输出)。

示例代码(修复后的)

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    output := exec.Command("git", "pull")
    stdout, err := output.StdoutPipe()

    output.Run()

    outBytes, err := ioutil.ReadAll(stdout)
    _ = err // TODO: Handle error

    fmt.Printf("stdout:\n%s\n", string(outBytes))
}

请根据实际情况调整代码,确保 shell 命令正确执行。

以上就是《GoLang exec.Command() 后台守护不执行 Shell 命令:如何解决?》的详细内容,更多关于的资料请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>