
golang exec.command 后台守护不执行 shell 问题
在使用 golang 的 exec.command() 命令在后台守护进程时,遇到程序运行但不执行 shell 命令的情况。以下是可能的原因和解决方案:
原因:exec.command() 的阻塞行为
cmd.run() 会阻塞当前 goroutine,直到命令执行完毕。然而,在后台守护模式下,由于主进程继续运行,cmd.run() 可能不会等到 shell 命令完成。
立即学习“go语言免费学习笔记(深入)”;
解决方案:使用 stdoutpipe() 获取 shell 输出
为了解决这个问题,可以使用 stdoutpipe() 获取 shell 命令输出的管道。这样,你可以从管道中读取输出,而不必等到命令执行完毕。
output := exec.command("ls")
stdout, err := output.stdoutpipe()
_ = err // todo: handle errorsupervisord 设置
在使用 supervisord 进行后台守护时,请确保 supervisord 配置正确地将输出管道连接到期望的日志文件中。
其他注意事项
示例代码(修复后的)
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 命令:如何解决?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号