英文:
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 <- true
}()
select {
case <-time.After(timeout):
fmt.Println("Timed out")
case <-finished:
fmt.Println("Successfully executed")
}
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 <- true
}()
select {
case <-time.After(timeout):
return false
case <-finished:
return true
}
}
func main() {
success := timeoutMyFunc(3*time.Second, func() {
/*
* Place your code here
*/
})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论