douhan8892 2017-08-20 11:28
浏览 149
已采纳

如何使用命名管道在go中处理过程输出

I am trying to set up a pipe from a running process in tmux,
in order to handle its output line by line.

I have had a look at this guide to pipe the output of a tmux session to stdout
and this article about (named) pipes in go.

I have been trying around with that for quite a while now,
but still didn't get any noteworthy results.

I would really appreciate any thoughts on how to set that pipe up,
Ideally in a way so I can range over it linewise.

Thanks a lot

  • 写回答

1条回答 默认 最新

  • duandou9931 2017-08-20 13:21
    关注

    Here is the solution which I found here (thank you Malcolm)

    func Readln(r *bufio.Reader) (string, error) {
        var (
            isPrefix = true
            err      error
            line, ln []byte
        )
        for isPrefix && err == nil {
            line, isPrefix, err = r.ReadLine()
            ln = append(ln, line...)
        }
        return string(ln), err
    }
    
    func handle(s string) {
        //Do something with your string
    }
    
    func main() {
        c := exec.Command("sh", "./tmuxpipe.sh")
        err := c.Run()
        if err != nil {
            log.Fatal(err)
        }
    
        f, err := os.Open("/tmp/tmuxpipe")
        if err != nil {
            fmt.Printf("error opening file: %v
    ", err)
            os.Exit(1)
        }
        r := bufio.NewReader(f)
        s, e := Readln(r)
        for e == nil {
            handle(s)
            log.Println(s)
            s, e = Readln(r)
        }
    }
    

    here is the tmuxpipe.sh:

    mkfifo /tmp/tmuxpipe
    tmux pipe-pane -o -t tmuxSession 'cat >> /tmp/tmuxpipe'
    

    The reason I did not just use exec.Command() there, is because for some reason beyond my comprehension this:

    c := exec.Command("tmux", "pipe-pane", "-o", "-t", "tmuxSession", 'cat >> /tmp/tmuxpipe'") 
    err := c.Run()
    handleError(err)
    

    did not work (for me). There was no error occuring, but the output of the tmux session wasn't displayd either.

    I hope this helps anybody

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 VB.NET2022如何生成发布成exe文件
  • ¥30 matlab appdesigner私有函数嵌套整合
  • ¥15 给我一个openharmony跑通webrtc实现视频会议的简单demo项目,sdk为12
  • ¥15 vb6.0使用jmail接收smtp邮件并另存附件到D盘
  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印