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 descriptorflags
.F_SETFD (int)
Set the file descriptor flags to the value specified byarg
.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 byarg
. 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 theFD_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 同学
Tornado 源码
flags = fcntl.fcntl(self._socket.fileno(), fcntl.F_GETFD)
flags |= fcntl.FD_CLOEXEC
fcntl.fcntl(self._socket.fileno(), fcntl.F_SETFD, flags)
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)