How to eject the CD Drive on Linux using C?
I was reading through this Advanced Linux Programming tutorial when I encountered a problem. I was trying to eject the CD-ROM drive using this code:
int fd = open(path_to_cdrom, O_RDONLY);
// Eject the CD-ROM drive
ioctl(fd, CDROMEJECT);
close(fd);
Then I try to compile this code and get the following output:
In file included from /usr/include/linux/cdrom.h:14,
from new.c:2:
/usr/include/asm/byteorder.h: In function ‘___arch__swab开发者_StackOverflow中文版32’:
/usr/include/asm/byteorder.h:19: error: expected ‘)’ before ‘:’ token
/usr/include/asm/byteorder.h: In function ‘___arch__swab64’:
/usr/include/asm/byteorder.h:43: error: expected ‘)’ before ‘:’ token
So what am I doing wrong?
The error message you're seeing looks like something is wrong in your #include lines, not with the code you posted. I tried compiling http://www.advancedlinuxprogramming.com/listings/chapter-6/cdrom-eject.c and it compiles just fine.
According to this, you need to specify O_NONBLOCK when opening the device, otherwise it won't work.
From that page:
cdrom = open(CDDEVICE,O_RDONLY | O_NONBLOCK)
You are missing a #include
, I think. Do you have:
#include <fcntl.h>
#include <linux/cdrom.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
Those are the ones in the example...
In the previous examples the following includes are not needed.
#include <sys/stat.h>
#include <sys/types.h>
Also as stated before you may need to open with O_NONBLOCK
You can find more options for interacting with the CDROM device in the header file located at '/usr/include/linux/cdrom.h' or here https://github.com/torvalds/linux/blob/master/include/uapi/linux/cdrom.h
Also here is another example for opening and closing the CD tray with the mentioned changes.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <linux/cdrom.h>
#include <sys/ioctl.h>
#include <unistd.h>
int main (int argc, char* argv[])
{
// Path to CD-ROM drive
char *dev = "/dev/dvd";
int fd = open(dev, O_RDONLY | O_NONBLOCK);
if(fd == -1){
printf("Failed to open '%s'\n", dev);
exit(1);
}
printf("fd :%d\n", fd);
// Eject the CD-ROM tray
ioctl (fd, CDROMEJECT);
sleep(2);
// Close the CD-ROM tray
ioctl (fd, CDROMCLOSETRAY);
close(fd);
return 0;
}
The open syscall has some unwanted behaviours which must be handled by setting it to Not blocking ie O_NONBLOCK Also check that you have included the header file
#include <linux/cdrom.h>
精彩评论