如何在Golang中监听FIFO并等待FIFO文件的输出

huangapple go评论69阅读模式
英文:

How to listen to fifo wait for a fifo file's output in golang

问题

我将运行一个命令,将输出推送到文件系统中的一个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("打开命名管道文件错误:", err)
	}

	reader := bufio.NewReader(file)

	for {
		_, err := reader.ReadBytes('\n')
		if err == nil {
			fmt.Println("cockroach server已启动")
			break
		}
	}

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

英文:

I'll run a command that will push output to a FIFO file in the file system.

In bash, I can write timeout 3000 cat server_fifo>server.url to wait until either the fifo was pushed an output, or it reaches the 3000 timeout.

I wonder how we can do this in golang, i.e. keep waiting for the output of an fifo file, and set a timeout for this wait.

Per matishsiao's gist script here, I know we can do

	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
		}
	}

But in this case, how to add a time out to the for loop?

答案1

得分: 3

这是一个简单的样板代码,你可以使用:

finished := make(chan bool)
go func() {
	/*
	 * 在这里放置你的代码
	 */
	finished <- true
}()
select {
case <-time.After(timeout):
	fmt.Println("超时")
case <-finished:
	fmt.Println("成功执行")
}

time.Second*3或任何Duration赋值给timeout变量。

编辑:添加带有回调函数的示例:

func timeoutMyFunc(timeout time.Duration, myFunc func()) bool {
	finished := make(chan bool)
	go func() {
		myFunc()
		finished <- true
	}()
	select {
	case <-time.After(timeout):
		return false
	case <-finished:
		return true
	}
}

func main() {
	success := timeoutMyFunc(3*time.Second, func() {
		/*
		 * 在这里放置你的代码
		 */
	})
}
英文:

This is a simple boilerplate you can use:

finished := make(chan bool)
go func() {
	/*
	 * Place your code here
	 */
	finished &lt;- true
}()
select {
case &lt;-time.After(timeout):
	fmt.Println(&quot;Timed out&quot;)
case &lt;-finished:
	fmt.Println(&quot;Successfully executed&quot;)
}

Assign time.Second*3 or any Duration to the timeout variable.

EDIT: Adding example function with callback:

func timeoutMyFunc(timeout time.Duration, myFunc func()) bool {
	finished := make(chan bool)
	go func() {
		myFunc()
		finished &lt;- true
	}()
	select {
	case &lt;-time.After(timeout):
		return false
	case &lt;-finished:
		return true
	}
}

func main() {
	success := timeoutMyFunc(3*time.Second, func() {
		/*
		 * Place your code here
		 */
	})
}

huangapple
  • 本文由 发表于 2021年11月8日 08:08:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/69877485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定