gpt4 book ai didi

go - 将大量数据写入 exec.Command().StdinPipe() 错误

转载 作者:IT王子 更新时间:2023-10-29 01:46:20 27 4
gpt4 key购买 nike

考虑以下 Go 代码片段:

cmd := exec.Command(program, arg0)
stdin, err := cmd.StdinPipe()
// produces error when b is too large
n, err := stdin.Write(b.Bytes())

只要 b 太大,Write() 就会返回一个错误。尝试过不同大小的 b 后,似乎只要 b 的长度长于 Linux 管道缓冲区大小时就会发生这种情况。有没有解决的办法?本质上,我需要通过标准输入将大型日志文件提供给外部脚本。

最佳答案

我写这个程序是为了测试你的代码:

package main

import "os/exec"
import "fmt"


func main() {
cmd := exec.Command("/bin/cat")

in, _ := cmd.StdinPipe()

cmd.Start()

for i := 1024*1024; ; i += 1024*1024 {
b := make([]byte,i)
n, err := in.Write(b)
fmt.Printf("%d: %v\n", n, err)
if err != nil {
cmd.Process.Kill()
return
}
}
}

这个程序给出错误的唯一方法是被调用的进程关闭标准输入。您调用的程序是否关闭标准输入?这可能是 Go 运行时中的错误。

关于go - 将大量数据写入 exec.Command().StdinPipe() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20993193/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com