Consider the func below.
func daemon(nochdir, noclose int) error {
var ret uintptr
var err syscall.Errno
ret, _, err = syscall.Syscall(syscall.SYS_FORK, 0, 0, 0)
if err != 0 {
return error(err)
}
switch ret {
case 0:
break
default:
os.Exit(0)
}
pid,r:=syscall.Setsid()
if pid==-1 || r!=nil{
return r
}
if nochdir == 0 {
os.Chdir("/")
}
if noclose == 0 {
f, e := os.OpenFile(os.DevNull, os.O_RDWR, 0)
if e != nil {
panic(e)
}
fd := f.Fd()
syscall.Dup2(int(fd), int(os.Stdin.Fd()))
f2, e := os.OpenFile("/var/log/mylog", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
if e != nil {
panic(e)
}
fd2 := f2.Fd()
syscall.Dup2(int(fd2), int(os.Stdout.Fd()))
syscall.Dup2(int(fd2), int(os.Stderr.Fd()))
}
return nil
}
The daemon func just fork the proc, and redirect the stdout and stderr to a log file.
But it doesn't work well. The child proc can't exist correctly and nothing can be written to the log file.
When I use
import _ "net" (just for side effect, right?)
It works(There may be some other problems, but the stdout is redirect right and the child proc exits)
And it seems that it's just due to the "net" package itself, not the packages it imported(it's useless to import os, syscall, runtime. etc...)
Does net package do anything when the proc is set up?
In addition, replace Syscall with RawSyscall works...