trayopen (archives)

I wrote a similar program in C that does the same thing, but with more states. See dvd_drive_status.

Archives

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);
}

Just download the code, and compile it with gcc:

gcc trayopen.c -o trayopen

Then, running it, it will return a 0 if it's open, or a 1 if it's closed.

Here's a sample bash script to call it:

#!/bin/bash
trayopen /dev/dvd
if [[ $? -eq 0 ]]; then
  echo "Open for business!"
elif [[ $? -eq 1 ]]; then
  echo "Sorry, already occupied."
fi

Navigation