Friday, May 3, 2024
12
rated 0 times [  12] [ 0]  / answers: 1 / hits: 3416  / 1 Year ago, mon, february 20, 2023, 12:32:45

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.


More From » command-line

 Answers
2

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]
");
printf("Result: Returns a 0 if the tray was open and 1 if it was closed
");
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.
",argv[1]);
exit(2);
}
/* Check CD tray status */
if (ioctl(cdrom,CDROM_DRIVE_STATUS) == CDS_TRAY_OPEN) {
status=0;
}

close(cdrom);
exit(status);
}

[#24624] Monday, February 20, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arkcker

Total Points: 296
Total Questions: 111
Total Answers: 104

Location: Nepal
Member since Tue, Sep 8, 2020
4 Years ago
arkcker questions
Tue, Aug 17, 21, 00:08, 3 Years ago
Sun, May 14, 23, 01:04, 1 Year ago
Wed, Nov 16, 22, 03:12, 1 Year ago
Tue, Jun 1, 21, 01:29, 3 Years ago
;