Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Golang 实现守护进程实例大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

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

大佬总结

以上是大佬教程为你收集整理的Golang 实现守护进程实例全部内容,希望文章能够帮你解决Golang 实现守护进程实例所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。