Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

Is there a command that you can run in a shell script that would detect if the CD tray is open or closed, and return 1 or 0 depending on whether it was (or something easy to interpret)?

Currently, I am executing the open command, and timing how long it takes to execute. If it is almost instant, it is open. If it takes time, it was open and is now closed.

I would like a method that doesn't involve changing the current state - just detecting it.

share|improve this question
    
Why do you need this? There is probably a simpler way to achieve whatever your end goal is. Do you just want to toggle the tray? –  terdon Jun 15 at 16:27
    
No, I do need to know if it is open as the aim is to be able to check, not togggle. I can toggle with eject -T. –  Tim Jun 15 at 16:31

1 Answer 1

up vote 5 down vote accepted

I found a nice little solution here. The C code below, minimally changed from the linked site, will return an exit code of 0 if the tray is open and 1 if it is not.

So, save this code as something (e.g. foo.c) and compile it with this command:

gcc -o trayopen foo.c

Then, copy the compiled executable, trayopen to /usr/bin:

sudo cp trayopen /usr/bin

You should no be able to do things like

trayopen /dev/sr0 && echo closed

Or, more complete:

#!/bin/sh
if trayopen /dev/sr0
then
    echo "Tray is open."
else
    echo "Tray is closed."
fi

The 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 (! argv[1] ){
    printf("Usage : trayopen [device]\n");
    printf("Result: Returns a 0 if the tray was open and 1 if it was closed\n");
    exit(2);
  }

  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(2);
  }
  /* Check CD tray status */
  if (ioctl(cdrom,CDROM_DRIVE_STATUS) == CDS_TRAY_OPEN) {
    status=0;
  }

  close(cdrom);
  exit(status);
}
share|improve this answer
    
Thankyou! Very nice, shame it isn't included in Linux / Ubuntu by default! –  Tim Jun 15 at 17:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.