Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if CD drive is open or closed in linux?

I'm making an application that requires the knowledge of whether a CD drive is open or closed.

eject opens the CD drive, and checks how long it takes to open (a shorter amount of time says it's open, and a longer, well...), but I cannot use this technique, because the application actually opens the drive (and I do not want to re-open the drive if it's closed, neither do I want to close the drive if it is open).

How would I do this on linux? I saw that it is possible to do this under Windows (might be wrong though), but I haven't seen a way of doing this on linux.

If it's not possible using linux API calls, is it possible to implement a low-level function that could do this?

like image 737
MiJyn Avatar asked Mar 27 '13 05:03

MiJyn


2 Answers

To make the example code work, you should do it this way:

#include <sys/ioctl.h>
#include <linux/cdrom.h>

int result=ioctl(fd, CDROM_DRIVE_STATUS, CDSL_NONE);

switch(result) {
  case CDS_NO_INFO: ... break;
  case CDS_NO_DISC: ... break;
  case CDS_TRAY_OPEN: ... break;
  case CDS_DRIVE_NOT_READY: ... break;
  case CDS_DISC_OK: ... break;
  default: /* error */
}

i.e. the result is returned as ioctl() function result, not into slot argument.

like image 98
user2846246 Avatar answered Sep 21 '22 18:09

user2846246


You can get tray state by using the CDROM_DRIVE_STATUS ioctl. All ioctls for CD-drives can be found in /usr/include/linux/cdrom.h

#define CDROM_DRIVE_STATUS      0x5326  /* Get tray position, etc. */

Taken from here

int slot;
ioctl(fd, CDROM_DRIVE_STATUS, slot);

switch(slot) {
  case CDS_NO_INFO: ... break;
  case CDS_NO_DISC: ... break;
  case CDS_TRAY_OPEN: ... break;
  case CDS_DRIVE_NOT_READY: ... break;
  case CDS_DISC_OK: ... break;
  default: /* error */
}
like image 21
fredrik Avatar answered Sep 19 '22 18:09

fredrik