golang 中创建daemon的方法

本文介绍了一种使用Go语言实现的进程分离技术,通过调用fork及setsid系统调用来创建新的进程并使其脱离父进程的控制。此技术在后台守护进程等场景中有着广泛的应用。

https://github.com/takama/daemon

 

https://github.com/immortal/immortal/blob/master/fork.go                  这个是比较原始的最接近c语言的实现,它里面还有很多原始c语言的东西的golang实现:

// fork.go
package immortal import (
"os" "os/exec" "syscall" ) // Fork crete a new process func Fork() (int, error) { args := os.Args[1:] cmd := exec.Command(os.Args[0], args...) cmd.Env = os.Environ() cmd.Stdin = nil cmd.Stdout = nil cmd.Stderr = nil cmd.ExtraFiles = nil cmd.SysProcAttr = &syscall.SysProcAttr{ // Setsid is used to detach the process from the parent (normally a shell) // // The disowning of a child process is accomplished by executing the system call // setpgrp() or setsid(), (both of which have the same functionality) as soon as // the child is forked. These calls create a new process session group, make the // child process the session leader, and set the process group ID to the process // ID of the child. https://bsdmag.org/unix-kernel-system-calls/ Setsid: true, } if err := cmd.Start(); err != nil { return 0, err } return cmd.Process.Pid, nil }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值