Go:将内容预先添加到顶部的输出

时间:2016-05-22 21:41:38

标签: go

在我的go程序中,我需要运行top来持续监控特定进程。但top没有给我记录每一行的时间戳。我正在考虑将它预先添加到我自己的输出中:

top := exec.Command("top", "-p", pid)
r, w := os.Pipe()
top.Stdout = w
top.Start()

这样我就可以在管道的一端读取r的输出。我想知道如果有来自top.Stdout的新行,我怎么能触发一个动作来获取当前时间戳并将其添加到输出中?我认为它应该像回调或Python的生成器,但我不确定如何在Go中执行它。

1 个答案:

答案 0 :(得分:1)

有些事情:

func main() {
    for ln := range topMon(2543) {
        fmt.Println(time.Now().UTC().Format(time.RFC3339), ln)
    }
}

func topMon(pids ...int) <-chan string {
    ch := make(chan string, 1)
    top := exec.Command("top", "-b")
    for _, pid := range pids {
        top.Args = append(top.Args, "-p", strconv.Itoa(pid))
    }
    r, w, _ := os.Pipe()
    go func() {
        sc := bufio.NewScanner(r)
        for sc.Scan() {
            ch <- sc.Text()
        }
        close(ch)
    }()
    top.Stdout = w
    top.Stderr = os.Stderr
    if err := top.Start(); err != nil {
        panic(err)
    }
    return ch
}

频道使用只是一个例子,你可以直接从管道返回rwader。