<p>I'd like to wrap the "tail -f" command for monitoring live file changes. I'm trying to read and handle each update to the stdout from tail -f and handle it. All the examples I see online are related to reading from STDOUT once from a command. I have not a clue of how I can go about doing this? Any ideas/recommendations/links? I'm grateful for any insight on this.</p>
<p>Thanks</p>
<hr/>**评论:**<br/><br/>lstokeworth: <pre><p>A very simple way to tail a file is:</p>
<pre><code>buf := make([]byte, 1024)
for {
n, err := f.Read(buf)
if n > 0 {
// do something with buf[:n]
}
if err == io.EOF {
time.Sleep(time.Second)
} else if err != nil {
// handle error
break
}
}
</code></pre>
<p>Adjust the sleep time up or down to taste.</p></pre>raff99: <pre><p>And that is, at the core, what "tail -f" does so you may want to just roll your own all in Go instead of trying to "tail the tail"</p></pre>Ajpennster: <pre><p>This is a pretty good approach. I may end up using this. Thanks</p></pre>earthboundkid: <pre><p>This feels like a classic <a href="http://xyproblem.info" rel="nofollow">XY problem</a>.</p></pre>djherbis: <pre><p>You might actually be interesting in something like: <a href="https://gopkg.in/fsnotify.v1" rel="nofollow">https://gopkg.in/fsnotify.v1</a></p></pre>Ajpennster: <pre><p>Thanks for the share. I'll definitely look into it but I'd prefer a solution that only requires the standard library. I'd also like to wrap "tail -f file.txt" instead of "reinventing the wheel"</p></pre>djherbis: <pre><p>StdoutPipe is what you want (as JRMWarfare says). However, if you want to act on each "update" it would probably be easier to use a library like fsnotify.</p>
<p>If all you want to do is redirect the bytes of the output somewhere else, then StdoutPipe will work.</p>
<p>Trying to detect each update via StdoutPipe will be hard since you'll just be getting a stream of bytes, you won't really get "updates" you'll just read more bytes.</p></pre>Ajpennster: <pre><p>I was thinking along those lines, reading every time stdout had bytes but I was a bit lost on how I'd achieve that. Most examples I've found were reading only once.</p></pre>sleepydog: <pre><p><a href="https://golang.org/pkg/bufio/#example_Scanner_lines" rel="nofollow">https://golang.org/pkg/bufio/#example_Scanner_lines</a></p></pre>JRMWarfare: <pre><p>os/exec has <a href="https://golang.org/pkg/os/exec/#Cmd.StdoutPipe" rel="nofollow">StdoutPipe</a>, which seems appropriate for what you're trying to do.</p>
<p>If I were you I would kick off a groutine where with a loop to monitor the pipe from the command which would write the output to a channel consumed by your primary operations.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传