github.com/rakyll/go@v0.0.0-20170216000551-64c02460d703/src/internal/poll/sock_cloexec.go (about)

     1  // Copyright 2013 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // This file implements sysSocket and accept for platforms that
     6  // provide a fast path for setting SetNonblock and CloseOnExec.
     7  
     8  // +build freebsd linux
     9  
    10  package poll
    11  
    12  import (
    13  	"syscall"
    14  )
    15  
    16  // Wrapper around the accept system call that marks the returned file
    17  // descriptor as nonblocking and close-on-exec.
    18  func accept(s int) (int, syscall.Sockaddr, string, error) {
    19  	ns, sa, err := Accept4Func(s, syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC)
    20  	// On Linux the accept4 system call was introduced in 2.6.28
    21  	// kernel and on FreeBSD it was introduced in 10 kernel. If we
    22  	// get an ENOSYS error on both Linux and FreeBSD, or EINVAL
    23  	// error on Linux, fall back to using accept.
    24  	switch err {
    25  	case nil:
    26  		return ns, sa, "", nil
    27  	default: // errors other than the ones listed
    28  		return -1, sa, "accept4", err
    29  	case syscall.ENOSYS: // syscall missing
    30  	case syscall.EINVAL: // some Linux use this instead of ENOSYS
    31  	case syscall.EACCES: // some Linux use this instead of ENOSYS
    32  	case syscall.EFAULT: // some Linux use this instead of ENOSYS
    33  	}
    34  
    35  	// See ../syscall/exec_unix.go for description of ForkLock.
    36  	// It is probably okay to hold the lock across syscall.Accept
    37  	// because we have put fd.sysfd into non-blocking mode.
    38  	// However, a call to the File method will put it back into
    39  	// blocking mode. We can't take that risk, so no use of ForkLock here.
    40  	ns, sa, err = AcceptFunc(s)
    41  	if err == nil {
    42  		syscall.CloseOnExec(ns)
    43  	}
    44  	if err != nil {
    45  		return -1, nil, "accept", err
    46  	}
    47  	if err = syscall.SetNonblock(ns, true); err != nil {
    48  		CloseFunc(ns)
    49  		return -1, nil, "setnonblock", err
    50  	}
    51  	return ns, sa, "", nil
    52  }