如何在golang中收听fifo等待fifo文件的输出

我将运行一个将输出推送到文件系统中的 FIFO 文件的命令。


在 bash 中,我可以写timeout 3000 cat server_fifo>server.url等到 fifo 被推送一个输出,或者它达到 3000 超时。


我想知道我们如何在 golang 中做到这一点,即一直等待 fifo 文件的输出,并为此等待设置超时。


根据 matishsiao 的 gist 脚本,我知道我们可以做到


    file, err := os.OpenFile(urlFileName, os.O_CREATE, os.ModeNamedPipe)

    if err != nil {

        log.Fatal("Open named pipe file error:", err)

    }


    reader := bufio.NewReader(file)


    for {

        _, err := reader.ReadBytes('\n')

        if err == nil {

            fmt.Println("cockroach server started")

            break

        }

    }

但是在这种情况下,如何在 for 循环中添加超时?


繁星淼淼
浏览 70回答 1
1回答

慕容3067478

这是您可以使用的简单样板:finished := make(chan bool)go func() {&nbsp; &nbsp; /*&nbsp; &nbsp; &nbsp;* Place your code here&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; finished <- true}()select {case <-time.After(timeout):&nbsp; &nbsp; fmt.Println("Timed out")case <-finished:&nbsp; &nbsp; fmt.Println("Successfully executed")}分配time.Second*3或任何Duration变量timeout。编辑:添加带有回调的示例函数:func timeoutMyFunc(timeout time.Duration, myFunc func()) bool {&nbsp; &nbsp; finished := make(chan bool)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; myFunc()&nbsp; &nbsp; &nbsp; &nbsp; finished <- true&nbsp; &nbsp; }()&nbsp; &nbsp; select {&nbsp; &nbsp; case <-time.After(timeout):&nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; case <-finished:&nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; success := timeoutMyFunc(3*time.Second, func() {&nbsp; &nbsp; &nbsp; &nbsp; /*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Place your code here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; })}这是您可以使用的简单样板:finished := make(chan bool)go func() {&nbsp; &nbsp; /*&nbsp; &nbsp; &nbsp;* Place your code here&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; finished <- true}()select {case <-time.After(timeout):&nbsp; &nbsp; fmt.Println("Timed out")case <-finished:&nbsp; &nbsp; fmt.Println("Successfully executed")}分配time.Second*3或任何Duration变量timeout。编辑:添加带有回调的示例函数:func timeoutMyFunc(timeout time.Duration, myFunc func()) bool {&nbsp; &nbsp; finished := make(chan bool)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; myFunc()&nbsp; &nbsp; &nbsp; &nbsp; finished <- true&nbsp; &nbsp; }()&nbsp; &nbsp; select {&nbsp; &nbsp; case <-time.After(timeout):&nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; case <-finished:&nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; success := timeoutMyFunc(3*time.Second, func() {&nbsp; &nbsp; &nbsp; &nbsp; /*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Place your code here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; })}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go