golang daemon usage example

  • 2020-06-01 09:59:05
  • OfStack

This article illustrates the use of the golang daemon as an example. I will share it with you for your reference as follows:

Using node wrote 1 socket background service, but sometimes hung,node1 exception is game over, so wrote 1 waiting.

package main
import (
        "log"
        "os"
        "os/exec"
        "time"
)
func main() {
        lf, err := os.OpenFile("angel.txt", os.O_CREATE | os.O_RDWR | os.O_APPEND, 0600)
        if err != nil {
                os.Exit(1)
        }
        defer lf.Close()
        // The log
        l := log.New(lf, "", os.O_APPEND)
        for {
                cmd := exec.Command("/usr/local/bin/node", "/*****.js")
                err := cmd.Start()
                if err != nil {
                        l.Printf("%s Startup command failed ", time.Now().Format("2006-01-02 15:04:05"), err)
                        time.Sleep(time.Second * 5)
                        continue
                }
                l.Printf("%s Process started ", time.Now().Format("2006-01-02 15:04:05"), err)
                err = cmd.Wait()
                l.Printf("%s Process exits ", time.Now().Format("2006-01-02 15:04:05"), err)
                time.Sleep(time.Second * 1)
        }
}

There is also an shell implementation. Remember to give execution permission,chmod +x you_command

#! /bin/bash
while true; do
    ./you_command
done

I hope this article has been helpful to you in programming Go.


Related articles: