I want to open the serial device exclusively by pyserial in ubuntu 20.04. I tried the following two approaches.
- To use the exclusive flag in pyserial.
ser = Serial(port=serialdevice, baudrate=115200, bytesize=8, timeout=2, exclusive=True)
- To use fcntl as below.
try:
ser = Serial(port=serialdevice, baudrate=115200, bytesize=8, timeout=2)
if ser.isOpen():
try:
fcntl.flock(ser.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except Exception as e:
print(e)
except Exception a e:
print(e)
Both approaches do not work. There is no any lock file generated under /var/lock.
Finally, I can only created the lock file manually under /var/lock as below.
try:
device_name = serialdevice.split("/")[2]
lock_file_name = "/var/lock/LCK.."+device_name
ser = Serial(port=serialdevice, baudrate=115200, bytesize=8, timeout=2)
if ser.isOpen():
open(lock_file_name, 'w').write(str(os.getpid()))
else:
print("port not open")
except Exception as e:
print("Failed to open serial port exclusively. Pls check if the serial port is already used by other tools")
print(e)
return
May I ask what could be wrong in the first two approaches? Is the manual method used generally in opening the serial port exclusively? Do I need to delete the lock file manually when the python script quit?
Thanks!