go-daemon

一个用 golang 编写系统守护进程的库。「A library for writing system daemons in golang.」

Github星跟踪图

go-daemon

用于在 Go 中编写系统守护进程的库。

现在只支持基于 UNIX 的操作系统(不支持 Windows)。但是这个库只在 Linux 和 OSX 上进行了测试,所以如果你有能力在其他平台上测试这个库,请给我反馈(#26)。

请随时给我发送错误报告和修复。非常感谢所有的贡献者。

特性

  • Goroutine 安全守护进程。
  • 开箱即用的 pid 文件。
  • 轻松处理系统信号。
  • 守护进程的控制。

安装

go get github.com/sevlyar/go-daemon

您也可以使用 gopkg.in:

go get gopkg.in/sevlyar/go-daemon.v0

如果你想在生产项目中使用该库,请使用 vendoring,因为在发布 v1.0 之前,我无法确保向后兼容。

示例

文档

godoc.org/github.com/sevlyar/go-daemon

它是如何工作的

我们不能在 Golang 的运行时使用 fork syscall,因为在这种情况下子进程不会继承线程和 goroutine。该库使用了一个简单的技巧:它运行自己的副本,并带有一个标记--一个预定义的环境变量。该变量对进程的可用性意味着在子进程的副本中执行。因此,如果没有设置标记--库会执行父库的操作,并运行带有标记的自己的副本,如果设置了标记--库会执行子库的操作。

func main() {
    Pre()

    context := new(Context)
    child, _ := context.Reborn()

    if child != nil {
        PostParent()
    } else {
        defer context.Release()
        PostChild()
    }
}


主要指标

概览
名称与所有者elixir-protobuf/protobuf
主编程语言Elixir
编程语言Go (语言数: 2)
平台Linux, Mac
许可证MIT License
所有者活动
创建于2017-02-23 16:38:38
推送于2025-06-18 08:16:34
最后一次提交
发布数28
最新版本名称v0.14.1 (发布于 2025-02-19 16:01:26)
第一版名称v0.1.0 (发布于 )
用户参与
星数873
关注者数13
派生数150
提交数505
已启用问题?
问题数153
打开的问题数13
拉请求数219
打开的拉请求数5
关闭的拉请求数35
项目设置
已启用Wiki?
已存档?
是复刻?
已锁定?
是镜像?
是私有?

go-daemon Build Status GoDoc

Library for writing system daemons in Go.

Now supported only UNIX-based OS (Windows is not supported). But the library was tested only on Linux
and OSX, so that if you have an ability to test the library on other platforms, give me feedback, please (#26).

Please, feel free to send me bug reports and fixes. Many thanks to all contributors.

Features

  • Goroutine-safe daemonization;
  • Out of box work with pid-files;
  • Easy handling of system signals;
  • The control of a daemon.

Installation

go get github.com/sevlyar/go-daemon

You can use gopkg.in:

go get gopkg.in/sevlyar/go-daemon.v0

If you want to use the library in production project, please use vendoring,
because i can not ensure backward compatibility before release v1.0.

Examples

Documentation

godoc.org/github.com/sevlyar/go-daemon

How it works

We can not use fork syscall in Golang's runtime, because child process doesn't inherit
threads and goroutines in that case. The library uses a simple trick: it runs its own copy with
a mark - a predefined environment variable. Availability of the variable for the process means
an execution in the child's copy. So that if the mark is not setted - the library executes
parent's operations and runs its own copy with mark, and if the mark is setted - the library
executes child's operations:

func main() {
	Pre()

	context := new(Context)
	child, _ := context.Reborn()

	if child != nil {
		PostParent()
	} else {
		defer context.Release()
		PostChild()
	}
}