[英]How to eject the CD Drive on Linux using C?
当我遇到问题时,我正在阅读这篇高级Linux编程教程。 我试图使用以下代码弹出CD-ROM驱动器:
int fd = open(path_to_cdrom, O_RDONLY);
// Eject the CD-ROM drive
ioctl(fd, CDROMEJECT);
close(fd);
然后我尝试编译此代码并获得以下输出:
In file included from /usr/include/linux/cdrom.h:14,
from new.c:2:
/usr/include/asm/byteorder.h: In function ‘___arch__swab32’:
/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
那么我做错了什么?
您看到的错误消息在#include行中看起来有问题,而不是您发布的代码。 我尝试编译http://www.advancedlinuxprogramming.com/listings/chapter-6/cdrom-eject.c并且它编译得很好。
我想你错过了#include
。 你有:
#include <fcntl.h>
#include <linux/cdrom.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
这些是示例中的那些......
在前面的示例中,不需要以下内容。
#include <sys/stat.h>
#include <sys/types.h>
如前所述,您可能需要使用O_NONBLOCK打开
您可以在位于'/usr/include/linux/cdrom.h'或https://github.com/torvalds/linux/blob/master/include/uapi的头文件中找到更多与CDROM设备交互的选项。 /linux/cdrom.h
此处还有另一个用上述更改打开和关闭CD托盘的示例。
#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;
}
open syscall有一些不需要的行为,必须通过将其设置为Not blocking即O_NONBLOCK来处理。还要检查是否已包含头文件
#include <linux/cdrom.h>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.