• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`!fcntl` --- The ``fcntl`` and ``ioctl`` system calls
2==========================================================
3
4.. module:: fcntl
5   :platform: Unix
6   :synopsis: The fcntl() and ioctl() system calls.
7
8.. sectionauthor:: Jaap Vermeulen
9
10.. index::
11   pair: UNIX; file control
12   pair: UNIX; I/O control
13
14----------------
15
16This module performs file and I/O control on file descriptors. It is an
17interface to the :c:func:`fcntl` and :c:func:`ioctl` Unix routines.
18See the :manpage:`fcntl(2)` and :manpage:`ioctl(2)` Unix manual pages
19for full details.
20
21.. availability:: Unix, not WASI.
22
23All functions in this module take a file descriptor *fd* as their first
24argument.  This can be an integer file descriptor, such as returned by
25``sys.stdin.fileno()``, or an :class:`io.IOBase` object, such as ``sys.stdin``
26itself, which provides a :meth:`~io.IOBase.fileno` that returns a genuine file
27descriptor.
28
29.. versionchanged:: 3.3
30   Operations in this module used to raise an :exc:`IOError` where they now
31   raise an :exc:`OSError`.
32
33.. versionchanged:: 3.8
34   The :mod:`!fcntl` module now contains ``F_ADD_SEALS``, ``F_GET_SEALS``, and
35   ``F_SEAL_*`` constants for sealing of :func:`os.memfd_create` file
36   descriptors.
37
38.. versionchanged:: 3.9
39   On macOS, the :mod:`!fcntl` module exposes the ``F_GETPATH`` constant,
40   which obtains the path of a file from a file descriptor.
41   On Linux(>=3.15), the :mod:`!fcntl` module exposes the ``F_OFD_GETLK``,
42   ``F_OFD_SETLK`` and ``F_OFD_SETLKW`` constants, which are used when working
43   with open file description locks.
44
45.. versionchanged:: 3.10
46   On Linux >= 2.6.11, the :mod:`!fcntl` module exposes the ``F_GETPIPE_SZ`` and
47   ``F_SETPIPE_SZ`` constants, which allow to check and modify a pipe's size
48   respectively.
49
50.. versionchanged:: 3.11
51   On FreeBSD, the :mod:`!fcntl` module exposes the ``F_DUP2FD`` and
52   ``F_DUP2FD_CLOEXEC`` constants, which allow to duplicate a file descriptor,
53   the latter setting ``FD_CLOEXEC`` flag in addition.
54
55.. versionchanged:: 3.12
56   On Linux >= 4.5, the :mod:`fcntl` module exposes the ``FICLONE`` and
57   ``FICLONERANGE`` constants, which allow to share some data of one file with
58   another file by reflinking on some filesystems (e.g., btrfs, OCFS2, and
59   XFS). This behavior is commonly referred to as "copy-on-write".
60
61.. versionchanged:: 3.13
62   On Linux >= 2.6.32, the :mod:`!fcntl` module exposes the
63   ``F_GETOWN_EX``, ``F_SETOWN_EX``, ``F_OWNER_TID``, ``F_OWNER_PID``, ``F_OWNER_PGRP`` constants, which allow to direct I/O availability signals
64   to a specific thread, process, or process group.
65   On Linux >= 4.13, the :mod:`!fcntl` module exposes the
66   ``F_GET_RW_HINT``, ``F_SET_RW_HINT``, ``F_GET_FILE_RW_HINT``,
67   ``F_SET_FILE_RW_HINT``, and ``RWH_WRITE_LIFE_*`` constants, which allow
68   to inform the kernel about the relative expected lifetime of writes on
69   a given inode or via a particular open file description.
70   On Linux >= 5.1 and NetBSD, the :mod:`!fcntl` module exposes the
71   ``F_SEAL_FUTURE_WRITE`` constant for use with ``F_ADD_SEALS`` and
72   ``F_GET_SEALS`` operations.
73   On FreeBSD, the :mod:`!fcntl` module exposes the ``F_READAHEAD``, ``F_ISUNIONSTACK``, and ``F_KINFO`` constants.
74   On macOS and FreeBSD, the :mod:`!fcntl` module exposes the ``F_RDAHEAD``
75   constant.
76   On NetBSD and AIX, the :mod:`!fcntl` module exposes the ``F_CLOSEM``
77   constant.
78   On NetBSD, the :mod:`!fcntl` module exposes the ``F_MAXFD`` constant.
79   On macOS and NetBSD, the :mod:`!fcntl` module exposes the ``F_GETNOSIGPIPE``
80   and ``F_SETNOSIGPIPE`` constant.
81
82The module defines the following functions:
83
84
85.. function:: fcntl(fd, cmd, arg=0)
86
87   Perform the operation *cmd* on file descriptor *fd* (file objects providing
88   a :meth:`~io.IOBase.fileno` method are accepted as well).  The values used
89   for *cmd* are operating system dependent, and are available as constants
90   in the :mod:`fcntl` module, using the same names as used in the relevant C
91   header files. The argument *arg* can either be an integer value, or a
92   :class:`bytes` object. With an integer value, the return value of this
93   function is the integer return value of the C :c:func:`fcntl` call.  When
94   the argument is bytes it represents a binary structure, e.g. created by
95   :func:`struct.pack`. The binary data is copied to a buffer whose address is
96   passed to the C :c:func:`fcntl` call.  The return value after a successful
97   call is the contents of the buffer, converted to a :class:`bytes` object.
98   The length of the returned object will be the same as the length of the
99   *arg* argument. This is limited to 1024 bytes. If the information returned
100   in the buffer by the operating system is larger than 1024 bytes, this is
101   most likely to result in a segmentation violation or a more subtle data
102   corruption.
103
104   If the :c:func:`fcntl` call fails, an :exc:`OSError` is raised.
105
106   .. audit-event:: fcntl.fcntl fd,cmd,arg fcntl.fcntl
107
108
109.. function:: ioctl(fd, request, arg=0, mutate_flag=True)
110
111   This function is identical to the :func:`~fcntl.fcntl` function, except
112   that the argument handling is even more complicated.
113
114   The *request* parameter is limited to values that can fit in 32-bits.
115   Additional constants of interest for use as the *request* argument can be
116   found in the :mod:`termios` module, under the same names as used in
117   the relevant C header files.
118
119   The parameter *arg* can be one of an integer, an object supporting the
120   read-only buffer interface (like :class:`bytes`) or an object supporting
121   the read-write buffer interface (like :class:`bytearray`).
122
123   In all but the last case, behaviour is as for the :func:`~fcntl.fcntl`
124   function.
125
126   If a mutable buffer is passed, then the behaviour is determined by the value of
127   the *mutate_flag* parameter.
128
129   If it is false, the buffer's mutability is ignored and behaviour is as for a
130   read-only buffer, except that the 1024 byte limit mentioned above is avoided --
131   so long as the buffer you pass is at least as long as what the operating system
132   wants to put there, things should work.
133
134   If *mutate_flag* is true (the default), then the buffer is (in effect) passed
135   to the underlying :func:`ioctl` system call, the latter's return code is
136   passed back to the calling Python, and the buffer's new contents reflect the
137   action of the :func:`ioctl`.  This is a slight simplification, because if the
138   supplied buffer is less than 1024 bytes long it is first copied into a static
139   buffer 1024 bytes long which is then passed to :func:`ioctl` and copied back
140   into the supplied buffer.
141
142   If the :c:func:`ioctl` call fails, an :exc:`OSError` exception is raised.
143
144   An example::
145
146      >>> import array, fcntl, struct, termios, os
147      >>> os.getpgrp()
148      13341
149      >>> struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, "  "))[0]
150      13341
151      >>> buf = array.array('h', [0])
152      >>> fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1)
153      0
154      >>> buf
155      array('h', [13341])
156
157   .. audit-event:: fcntl.ioctl fd,request,arg fcntl.ioctl
158
159
160.. function:: flock(fd, operation)
161
162   Perform the lock operation *operation* on file descriptor *fd* (file objects providing
163   a :meth:`~io.IOBase.fileno` method are accepted as well). See the Unix manual
164   :manpage:`flock(2)` for details.  (On some systems, this function is emulated
165   using :c:func:`fcntl`.)
166
167   If the :c:func:`flock` call fails, an :exc:`OSError` exception is raised.
168
169   .. audit-event:: fcntl.flock fd,operation fcntl.flock
170
171
172.. function:: lockf(fd, cmd, len=0, start=0, whence=0)
173
174   This is essentially a wrapper around the :func:`~fcntl.fcntl` locking calls.
175   *fd* is the file descriptor (file objects providing a :meth:`~io.IOBase.fileno`
176   method are accepted as well) of the file to lock or unlock, and *cmd*
177   is one of the following values:
178
179   .. data:: LOCK_UN
180
181      Release an existing lock.
182
183   .. data:: LOCK_SH
184
185      Acquire a shared lock.
186
187   .. data:: LOCK_EX
188
189      Acquire an exclusive lock.
190
191   .. data:: LOCK_NB
192
193      Bitwise OR with any of the other three ``LOCK_*`` constants to make
194      the request non-blocking.
195
196   If :const:`!LOCK_NB` is used and the lock cannot be acquired, an
197   :exc:`OSError` will be raised and the exception will have an *errno*
198   attribute set to :const:`~errno.EACCES` or :const:`~errno.EAGAIN` (depending on the
199   operating system; for portability, check for both values).  On at least some
200   systems, :const:`!LOCK_EX` can only be used if the file descriptor refers to a
201   file opened for writing.
202
203   *len* is the number of bytes to lock, *start* is the byte offset at
204   which the lock starts, relative to *whence*, and *whence* is as with
205   :func:`io.IOBase.seek`, specifically:
206
207   * ``0`` -- relative to the start of the file (:const:`os.SEEK_SET`)
208   * ``1`` -- relative to the current buffer position (:const:`os.SEEK_CUR`)
209   * ``2`` -- relative to the end of the file (:const:`os.SEEK_END`)
210
211   The default for *start* is 0, which means to start at the beginning of the file.
212   The default for *len* is 0 which means to lock to the end of the file.  The
213   default for *whence* is also 0.
214
215   .. audit-event:: fcntl.lockf fd,cmd,len,start,whence fcntl.lockf
216
217Examples (all on a SVR4 compliant system)::
218
219   import struct, fcntl, os
220
221   f = open(...)
222   rv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NDELAY)
223
224   lockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
225   rv = fcntl.fcntl(f, fcntl.F_SETLKW, lockdata)
226
227Note that in the first example the return value variable *rv* will hold an
228integer value; in the second example it will hold a :class:`bytes` object.  The
229structure lay-out for the *lockdata* variable is system dependent --- therefore
230using the :func:`flock` call may be better.
231
232
233.. seealso::
234
235   Module :mod:`os`
236      If the locking flags :const:`~os.O_SHLOCK` and :const:`~os.O_EXLOCK` are
237      present in the :mod:`os` module (on BSD only), the :func:`os.open`
238      function provides an alternative to the :func:`lockf` and :func:`flock`
239      functions.
240