fcntl

Description

int fcntl(int fd, int cmd, ... /* arg */ );

fcntl() performs one of the operations on the open file descriptor fd. The operation is determined by cmd.

  • cmd

    • F_GETFD (void)
      Read the file descriptor flags; arg is ignored.
      Return value of file descriptor flags.

    • F_SETFD (int)
      Set the file descriptor flags to the value specified by arg.

    • F_GETFL (void)
      Get the file access mode and the file status flags; arg is ignored.

    • F_SETFL (int)
      Set the file status flags to the value specified by arg. File access mode (O_RDONLY, O_WRONLY, O_RDWR) and file creation flags (i.e., O_CREAT, O_EXCL, O_NOCTTY, O_TRUNC) in arg are ignored. On Linux this command can change only the O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME, and O_NONBLOCK flags.

  • File descriptor flags v.s. File status flags

    • File descriptor flags
      The F_GETFD and F_SETFD commands manipulate the flags associated with a file descriptor. FD_CLOEXEC, the close-on-exec flag. If the FD_CLOEXEC bit is 0, the file descriptor will remain open across an execve(2), otherwise it will be closed.

    • File status flags
      Each open file description has certain associated status flags, initialized by open(2) and possibly modified by fcntl().

下图来自 xbf 同学

fcntl_第1张图片
707631-20151103194228883-452884438.jpg

Tornado 源码

  • Tornado v1.0.0/ httpserver.py
 flags = fcntl.fcntl(self._socket.fileno(), fcntl.F_GETFD)
 flags |= fcntl.FD_CLOEXEC
 fcntl.fcntl(self._socket.fileno(), fcntl.F_SETFD, flags)
  • Tornado v1.0.0/ ioloop.py
    def _set_nonblocking(self, fd):
        flags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)

    def _set_close_exec(self, fd):
        flags = fcntl.fcntl(fd, fcntl.F_GETFD)
        fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)

read more

  • fcntl(2) - Linux man page

  • fcntl使用及FD_CLOEXEC详解

  • 关于fd的close on exec(非常重要)

你可能感兴趣的:(fcntl)