The fcntl and ioctl System Calls in Python

PythonProgrammingServer Side Programming

To control the files and the io, we should use the fcntl module. It is basically one interface to the fcntl() and ioctl() Unix routines.

All methods in this module takes one integer or io.IOBase file-descriptor as their first argument.

To use this module, we should import it using.

import fcntl

There are some modules of the fcntl module, these are −

Method fcntl.fcntl(fd, op[, arg])

This method is used to perform the operation on the file using file descriptor. The operation is defined by op. The third argument is optional. It can be either integer type value or string type value. When the argument is integer type, the return value will be the value of C fcntl() call. When it is string, it represents binary structure. When this function fails, it raises an IOError.

Method fcntl.ioctl(fd, op[, arg[, mutate_flag]])

This method is identical to the fcntl() method, but in this case the argument handling is more complex. In the argument, if the mutable buffer is passed, then its behavior will depend on the mutate_flag. When it is true, the buffer can be mutable, otherwise it will act like read-only buffer.

Method fcntl.flock(fd, op)

This method is used to perform lock operation op on the file using file_descriptor. On some systems, this method can be emulated using the fcntl() method.

Method fcntl.lockf(fd, operation[, length[, start[, whence]]])

This method is used to perform as a wrapper around the locking calls. The operation argument is passed to lock or unlock the file. There are different values of operation.

  • LOCK_UN − To unlock the file

  • LOCK_SH − Shared Lock

  • LOCK_EX − Exclusive Lock

Example Code

Live Demo

import fcntl, os, time
counter_file = 'my_counter.txt'
if not os.path.exists(counter_file):
   counter_file = open('my_counter.txt', 'w')
   counter_file.write('0') #Store 0 as starting number
for i in range(15):
   counter_file = open('my_counter.txt', 'r+')
   fcntl.flock(counter_file.fileno(), fcntl.LOCK_EX)
   count = int(counter_file.readline()) + 1
   print('Process ID: ' + str(os.getpid()) + ', Count: ' + str(count))


$ python3
Process ID: 12698, Count: 1
Process ID: 12698, Count: 2
Process ID: 12698, Count: 3
Process ID: 12698, Count: 4
Process ID: 12698, Count: 5
Process ID: 12698, Count: 6
Process ID: 12698, Count: 7
Process ID: 12698, Count: 8
Process ID: 12698, Count: 9
Process ID: 12698, Count: 10
Process ID: 12698, Count: 11
Process ID: 12698, Count: 12
Process ID: 12698, Count: 13
Process ID: 12698, Count: 14
Process ID: 12698, Count: 15
$ cat my_counter.txt
Published on 31-Oct-2018 18:04:24