douqiao7188 2017-08-01 16:44
浏览 108
已采纳

从命名管道连续读取

I would like to know what other options I have in order to read continuously from a named pipe using golang. My current code relies on a infinite for loop running inside a gorutine; but hat keeps one CPU at 100% usage.

func main() {
....

var wg sync.WaitGroup
fpipe, _ := os.OpenFile(namedPipe, os.O_RDONLY, 0600)
defer fpipe.Close()

f, _ := os.Create("dump.txt")
defer f.Close()
var buff bytes.Buffer

wg.Add(1)
go func() {
        for {
          io.Copy(&buff, fpipe)
          if buff.Len() > 0 {
              buff.WriteTo(f)
           }
         }
    }()

    wg.Wait()
}
  • 写回答

2条回答 默认 最新

  • dongtaoxue4674 2017-08-01 17:09
    关注

    A named pipe reader will receive EOF when there are no writers left. The solution outside of this code is to make sure there is always one writer process holding the file descriptor, though it doesn't need to write anything.

    Within the Go program, if you want to wait for a new writer, you will have to poll the io.Reader in your for loop. Your current code does this with a busy loop, which will consume 100% of 1 cpu core. Adding a sleep and a way to return on other errors will work around the issue:

    for {
        err := io.Copy(&buff, fpipe)
        if buff.Len() > 0 {
            buff.WriteTo(f)
        }
    
        if err != nil {
            // something other than EOF happened
            return
        }
    
        time.Sleep(100 * time.Millisecond)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法