Example #1
0
func main() {
	flag.Parse()
	daemon.AddCommand(daemon.StringFlag(signal, "quit"), syscall.SIGQUIT, termHandler)
	daemon.AddCommand(daemon.StringFlag(signal, "stop"), syscall.SIGTERM, termHandler)

	error := gcfg.ReadFileInto(&cfg, "config")
	if error != nil {
		fmt.Println(error)
		return
	}

	cntxt := &daemon.Context{
		PidFileName: cfg.General.PidFileName,
		PidFilePerm: 0644,
		LogFileName: cfg.General.LogFileName,
		LogFilePerm: 0640,
		WorkDir:     "./",
		Umask:       027,
		Args:        []string{},
	}

	if len(daemon.ActiveFlags()) > 0 {
		d, err := cntxt.Search()
		if err != nil {
			log.Fatalln("Unable send signal to the daemon:", err)
		}
		daemon.SendCommands(d)
		return
	}

	d, err := cntxt.Reborn()
	if err != nil {
		log.Fatalln(err)
	}
	if d != nil {
		return
	}
	defer cntxt.Release()

	log.Println("- - - - - - - - - - - - - - -")
	log.Println("daemon started")

	go worker()

	err = daemon.ServeSignals()
	if err != nil {
		log.Println("Error:", err)
	}
	log.Println("daemon terminated")
}
Example #2
0
func Daemonize(childMain postChild, termHandler dmn.SignalHandlerFunc) {
	dmn.SetSigHandler(termHandler, syscall.SIGTERM)
	dmn.SetSigHandler(termHandler, syscall.SIGQUIT)

	// Don't restart it if its running!
	if IsDaemonized() {
		return
	}

	child, err := context.Reborn()

	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
		}).Fatal("could not recreate context!")
	}

	if child != nil {
		isdmn = false
		return
	} else {
		defer context.Release()
		isdmn = true

		go childMain()

		err = dmn.ServeSignals()
		if err != nil {
			log.WithFields(log.Fields{
				"error": err,
			}).Fatal("error occured")
		}

		os.Exit(0)
	}
}