something about daemon

419 views
Skip to first unread message

Ruiqi Hong

unread,
Mar 7, 2012, 2:50:03 AM3/7/12
to golan...@googlegroups.com
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... 

Paul Borman

unread,
Mar 7, 2012, 11:07:58 AM3/7/12
to Ruiqi Hong, golan...@googlegroups.com
If your process has more than a single kernel thread you will have a problem.  The child of fork will only have a single kernel thread.  If you consider the only reason for fork is to call exec then it makes sense.  (I don't agree with that line, but many do, look at the justifications given for vfork.)

    -Paul

Alexandre Fiori

unread,
Oct 25, 2013, 11:31:52 AM10/25/13
to golan...@googlegroups.com
It doesn't work well. Check this out: https://code.google.com/p/go/issues/detail?id=227
Reply all
Reply to author
Forward
0 new messages