This is an old revision of the document!


trayopen

This code has been a lifesaver to me when it comes to checking to see if a tray is open or not. Believe it or not, there's nothing good out there to query it! (And I've looked, too.)

Enter trayopen, a small piece of C code that was posted on the linux questions forums by volkerdi. (thanks!)

Here's the complete code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <linux/cdrom.h>

int main(int argc,char **argv) {
  int cdrom;
  int status=1;

  if(argc == 0) {
    printf("Usage: trayopen [device]\n");
    printf("Result: Open tray exit code 0, closed tray exit code 1.\n");
  }

  if ((cdrom = open(argv[1],O_RDONLY | O_NONBLOCK)) < 0) {
    printf("Unable to open device %s. Provide a device name (/dev/sr0, /dev/cdrom) as a parameter.\n",argv[1]);
    exit(1);
  }

  if (ioctl(cdrom,CDROM_DRIVE_STATUS) == CDS_TRAY_OPEN) {
    status=0;
  }

  close(cdrom);
  exit(status);
}

Navigation