Go语言daemon启动的解决方法.linux平台

fyxichen · · 4195 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

1、使用nohup ./commond & 这种方法最简单.
2、这种方法可以使用信号.
<pre name="code" class="html">package main

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	if os.Getppid() != 1 {
		args := append([]string{os.Args[0]}, os.Args[1:]...)
		os.StartProcess(os.Args[0], args, &os.ProcAttr{Files: []*os.File{os.Stdin, os.Stdout, os.Stderr}})
		return
	}
	go func() {
		var c chan os.Signal = make(chan os.Signal, 1)
		go signal.Notify(c, os.Kill, os.Interrupt, syscall.SIGHUP, syscall.SIGUSR2)
		File, err := os.Create("/tmp/收到的信号.")
		defer File.Close()
		for {
			s := <-c
			File.WriteString(s.String())
		}
	}()
	F, err := os.Create("/tmp/log")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer F.Close()
	for {
		fmt.Fprintln(F, "Hello World")
		time.Sleep(3e9)
	}
}


3、这种方法比较底层,但是不能使用信号.
package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"runtime"
	"syscall"
	"time"
)

func daemon(nochdir, noclose int) int {
	var ret, ret2 uintptr
	var err syscall.Errno
	darwin := runtime.GOOS == "darwin"
	// already a daemon
	if syscall.Getppid() == 1 {
		return 0
	}
	// fork off the parent process
	ret, ret2, err = syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
	if err != 0 {
		return -1
	}
	// failure
	if ret2 < 0 {
		os.Exit(-1)
	}
	// handle exception for darwin
	if darwin && ret2 == 1 {
		ret = 0
	}
	// if we got a good PID, then we call exit the parent process.
	if ret > 0 {
		os.Exit(0)
	}
	/* Change the file mode mask */
	_ = syscall.Umask(0)

	// create a new SID for the child process
	s_ret, s_errno := syscall.Setsid()
	if s_errno != nil {
		log.Printf("Error: syscall.Setsid errno: %d", s_errno)
	}
	if s_ret < 0 {
		return -1
	}
	if nochdir == 0 {
		os.Chdir("/")
	}
	if noclose == 0 {
		f, e := os.OpenFile("/dev/null", os.O_RDWR, 0)
		if e == nil {
			fd := f.Fd()
			syscall.Dup2(int(fd), int(os.Stdin.Fd()))
			syscall.Dup2(int(fd), int(os.Stdout.Fd()))
			syscall.Dup2(int(fd), int(os.Stderr.Fd()))
		}
	}
	return 0
}

func main() {
	daemon(0, 1)
	for {
		fmt.Println("hello")
		time.Sleep(1 * time.Second)
	}
}


有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:fyxichen

查看原文:Go语言daemon启动的解决方法.linux平台

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

4195 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传