scratch/misc/open_tray_linux.c
2024-12-26 14:02:40 -03:00

38 lines
761 B
C

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <linux/cdrom.h>
#include <sys/ioctl.h>
int main(void)
{
// Open cdrom device, it must be opened in non-blocking mode
int cdfd = open("/dev/cdrom", O_RDONLY | O_NONBLOCK);
if (cdfd < 0) {
perror("open");
return 1;
}
int cdrom_stat = ioctl(cdfd, CDROM_DRIVE_STATUS, 0);
if ((cdrom_stat > -1 && cdrom_stat != CDS_NO_INFO) &&
cdrom_stat == CDS_TRAY_OPEN) {
printf("tray is already open\n");
return 0;
}
// Issue eject command
if (ioctl(cdfd, CDROMEJECT, 0) < 0) {
if (errno == EBUSY) {
fputs("either another process is using the drive or the door is locked.\n", stderr);
return 1;
}
perror("ioctl");
return 1;
}
close(cdfd);
return 0;
}