加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang 实现守护进程实例

发布时间:2020-12-16 09:32:22 所属栏目:大数据 来源:网络整理
导读: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.Getp

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)
  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)   }}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读