xdaemon

package
v1.3.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 19, 2025 License: MIT, MIT Imports: 7 Imported by: 3 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

xdaemon

兼容Windows/Linux的自守护和后台运行库.

forked from zh-five/xdaemon

A library for writing system daemons in golang. 一个让go程序快速后台运行的库. 支持linux和windows

两种运行模式

1.纯后台进程模式

请参考 example/background.go

//本示例, 将把进程转为后台运行, 并保留所有参数不变
package main

import (
	"github.com/fufuok/utils/xdaemon"
	"log"
	"os"
	"time"
)

func main() {
	logFile := "daemon.log"

	//启动一个子进程后主程序退出
	xdaemon.Background(logFile, true)

	//以下代码只有子程序会执行
	log.Println(os.Getpid(), "start...")
	time.Sleep(time.Second * 10)
	log.Println(os.Getpid(), "end")
}

2.守护进程模式

  • 运行主进程时, 启动一个守护进程后退出
  • 守护进程启动一个最终的子进程
  • 若最终子进程退出, 守护进程将尝试再次启动
  • 支持最大重启次数等一些参数的设置
  • 最终系统中会存在两个进程:守护进程和最终子进程

请参考 example/auto_restart.go

//本示例, 将把进程转为后台运行, 并保留所有参数不变
package main

import (
	"github.com/fufuok/utils/xdaemon"
	"log"
	"os"
	"time"
)

func main() {
	logFile := "daemon.log"

	//启动一个子进程后主程序退出
	xdaemon.Background(logFile, true)

	//以下代码只有子程序会执行
	log.Println(os.Getpid(), "start...")
	time.Sleep(time.Second * 10)
	log.Println(os.Getpid(), "end")
}

3.本次开发过程的博客记录

https://zhuanlan.zhihu.com/p/146192035

Documentation

Index

Constants

View Source
const EnvName = "XW_DAEMON_IDX"

Variables

This section is empty.

Functions

func Background

func Background(logFile string, isExit bool) (*exec.Cmd, error)

Background 把本身程序转化为后台运行(启动一个子进程, 然后自己退出) logFile 若不为空,子程序的标准输出和错误输出将记入此文件 isExit 启动子加进程后是否直接退出主程序, 若为false, 主程序返回*os.Process, 子程序返回 nil. 需自行判断处理

func NewSysProcAttr

func NewSysProcAttr() *syscall.SysProcAttr

Types

type Daemon

type Daemon struct {
	LogFile     string // 日志文件, 记录守护进程和子进程的标准输出和错误输出. 若为空则不记录
	MaxCount    int    // 循环重启最大次数, 若为0则无限重启
	MaxError    int    // 连续启动失败或异常退出的最大次数, 超过此数, 守护进程退出, 不再重启子进程
	MinExitTime int64  // 子进程正常退出的最小时间(秒). 小于此时间则认为是异常退出
}

Daemon 守护进程

func NewDaemon

func NewDaemon(logFile string) *Daemon

func (*Daemon) Run

func (d *Daemon) Run()

Run 启动后台守护进程

Directories

Path Synopsis
examples
auto_restart command
本示例, 将启动一个后台运行的守护进程.
本示例, 将启动一个后台运行的守护进程.
background command
本示例, 将把进程转为后台运行, 并保留所有参数不变
本示例, 将把进程转为后台运行, 并保留所有参数不变

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL