之前用过很多方式,包括
&
nohup
模拟fork
用centos 7之后,发现最好的办法是作为systemd的service,Type为notify方式
一个简单的示例
service单元文件编写
[Unit] Description=ewar gate server After=network.target [Service] Type=notify PIDFile=/usr/local/ewar/run/chat.pid ExecStartPre=/bin/rm -f /usr/local/ewar/run/chat.pid ExecStart=/usr/local/ewar/bin/chat -c /usr/local/ewar/etc/chat.ini --pidfile=/usr/local/ewar/run/chat.pid --log_dir=/usr/local/ewar/log ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s QUIT $MAINPID
Go程序
socketAddr := &net.UnixAddr{ Name: os.Getenv("NOTIFY_SOCKET"), Net: "unixgram", } if socketAddr.Name == "" { return SdNotifyNoSocket } conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr) if err != nil { return err } defer conn.Close() _, err = conn.Write([]byte("READY=1"))
启动完成后向systemd汇报,完成启动
之后就能用systemd管理start stop restart等等