Black Lives Matter. Support the Equal Justice Initiative.

Source file src/internal/poll/sock_cloexec.go

Documentation: internal/poll

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

View as plain text