Golang 实现守护进程实例

本文详细介绍了使用Go语言实现守护进程的过程,包括如何通过fork创建子进程、改变文件权限、设置新的会话ID、修改进程工作目录以及重定向IO流等关键步骤。

package main

import (
  "fmt"
  "os"
  "os/signal"
  "runtime"
  "time"

  "log"
  "syscall"
)

func Agent(nochdir,noclose int) int {
  var ret1,ret2 uintptr
  var err syscall.Errno

  darwin := runtime.GOOS == "darwin"

  //already a daemon process
  if syscall.Getppid() == 1 {
    return 0
  }

  //fork off the parent process
  ret1,ret2,err = syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
  if err != 0 {
    return -1
  }

  //failure
  if ret2 < 0 {
    os.Exit(-1)
  }

  //hand exception for darwin
  if darwin && ret2 == 1 {
    ret1 = 0
  }

  //new process success, exit the parent process
  if ret1 > 0 {
    os.Exit(0)
  }

  //change the filem mode mask
  _ = syscall.Umask(0)

  //create the new SID for the child process
  s_ret,s_errno := syscall.Setsid()
  if s_errno != nil {
    log.Printf("Error: syscall.Setsid error:%d",s_errno)
  }

  if s_ret < 0 {
    return -1
  }

  //modify the process execute directory
  if nochdir == 0 {
    os.Chdir("/")
  }

  //redirect the IO stream
  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()))
    }
  }
  fmt.Println(os.Getpid())
  return 0
}

func main() {
  fmt.Println("Hello, World.\n")
  fmt.Println(os.Getpid())
  fmt.Println("this is a first go program!")
  Agent(0,1)
  for {
    fmt.Println("hello")
    fmt.Println(os.Getpid())
    time.Sleep(1 * time.Second)
  }
}

转载于:https://www.cnblogs.com/chmyee/p/9970692.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值