I'm using the great "evdev" library to listen to a USB barcode reader input and I need to detect if the device suddenly gets unplugged/unresponsive because otherwise the python script reading the loop goes to 100% cpu usage on a single thread and slowly starts to eat all available memory which leads to the entire system crashing after a bit.
The idea is to detect when the device is unplugged and kill the current script leading to supervisor trying to restart it until the device is plugged back in/becomes responsive.
The code I'm using to read the input is as follows:
devices = map(InputDevice, list_devices())
keys = {
2: 1,
3: 2,
4: 3,
5: 4,
6: 5,
7: 6,
8: 7,
9: 8,
10: 9,
11: 0,
}
dev = None
for d in devices:
if d.name == 'Symbol Technologies, Inc, 2008 Symbol Bar Code Scanner':
print('%-20s %-32s %s' % (d.fn, d.name, d.phys))
dev = InputDevice(d.fn)
break
if dev is not None:
code = []
for event in dev.read_loop():
if event.type == ecodes.EV_KEY:
if event.value == 00:
if event.code != 96:
try:
code.append(keys[event.code])
except:
code.append('-')
else:
card = "".join(map(str, code))
print card
code = []
card = ""
So how would I go about doing this the proper way?
A way I though that might work would be a second script that's run from cron every 1-5 min that checks if said device is still available, if it's now, grab process id from some file and kill the process that way but the problem with this method is that if the device is unplugged and then plugged back between the checks the "checker" script thinks everything is okay while the main script is slowly crashing - it doesn't re-activate after an "unplugging"