I would like for my program to do something when a CD is put in the CD drive. The method I devised is this:
def start_cddrive_watcher(self):
CDROM_DRIVE = '/dev/cdrom'
fd = os.open(CDROM_DRIVE, os.O_RDONLY | os.O_NONBLOCK)
# 0x5326 = CDROM_DRIVE_STATUS (see linux/cdrom.h).
# Status values:
# 1 = no disc
# 2 = tray open
# 3 = drive getting ready
# 4 = disc ready
def poll_status():
status = fcntl.ioctl(fd, 0x5326)
do_something(status)
return True
GLib.timeout_add_seconds(1, poll_status)
This code works, but I am wondering whether there is a better way to solve the problem using something like GLib.io_add_watch. Would it be more efficient to somehow have the OS signal when there is a change in status rather than have GLib constantly poll, or is GLib’s polling is so efficient that any other solution would be gratuitous optimization?