【发布时间】:2017-11-22 15:50:52
【问题描述】:
我想守护 myapp,但我有一个大问题。我使用的频道类型为chan struct{}。
但是,使用包 getopt(标志包),我的标志是 *bool 类型的,所以我不知道如何修改 myapp。
频道类型 bool 是不够的。我确定有一个我不明白的概念。我附上代码:
package main
import (
"os"
"syscall"
"time"
"github.com/pborman/getopt/v2"
"github.com/sevlyar/go-daemon"
)
var (
done = make(chan struct{})
optQuit = make(chan struct{})
optRun = make(chan struct{})
)
func TermHandler(sig os.Signal) error {
optQuit <- struct{}{}
if sig == syscall.SIGQUIT {
<-done
}
return nil
}
func main() {
optHelp := getopt.BoolLong("help", 'h', "Help")
optQuit := getopt.BoolLong("quit", 0, "Help")
optRun := getopt.BoolLong("run", 'r', "Help")
if *optHelp {
getopt.Usage()
os.Exit(0)
}
// Create pid file
cntxt := &daemon.Context{
PidFileName: "/var/run/myapp.pid",
PidFilePerm: 0644,
WorkDir: "./",
Umask: 027,
Args: []string{"[Z]"},
}
if len(daemon.ActiveFlags()) > 0 {
d, _ := cntxt.Search()
daemon.SendCommands(d)
return
}
d, err := cntxt.Reborn()
if d != nil {
return
}
if err != nil {
os.Exit(1)
}
defer cntxt.Release()
// Define ticker
ticker := time.NewTicker(time.Second)
myapp := true
// Loop
for myapp {
select {
// Case sleep
case <- ticker.C:
time.Sleep(time.Second)
// Case QUIT
case <- optQuit:
done <- struct{}{}
myapp = false
ticker.Stop()
os.Exit(0)
// Case RUN
case <- optRun:
// Executes a goroutine...
}
}
}
使用go install,我可以看到这个错误:
./main.go:72: invalid operation: <-optQuit (receive from non-chan type *bool)
./main.go:79: invalid operation: <-optRun (receive from non-chan type *bool)
我不知道应该如何修改通道(完成,struct{} 类型的 optQuit)来解决这个问题...
P.S.:我给你看一个我做过的例子。它作为守护进程运行,每分钟执行 Writer() 函数。
之后,如果您键入 zdaemon -z quit,应用程序会正常关闭。你可以在你的机器上运行它:
【问题讨论】:
-
这里似乎有点跑题了,不妨试试codereview.stackexchange.com
标签: pointers go struct daemon channel