some more functions related to fcntl and ioctl














































some more functions related to fcntl and ioctl



some more functions related to fcntl and ioctl:

fcntl.flock(fd, op)

This function 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.

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

This function 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


here is an example code for better understanding:

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

here is the output:
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
15



 


Comments