#include <fcntl.h>
#include <linux/cdrom.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
int main(void)
{
int fd = open("/dev/cdrom", O_RDONLY | O_NONBLOCK);
if (fd == -1)
{
printf("Failed opening CD-ROM.\n");
return -1;
}
if (!ioctl(fd, CDROMEJECT, NULL))
printf("Ejected CD-ROM successfully.\n");
else
printf("Failed ejecting CD-ROM.\n");
close(fd);
return 0;
}
由于open光驱时,可能光驱中没有光盘,因此需要使用O_NONBLOCK选项,否则open会失败(系统默认为我们打开这个光驱的目的是查看光盘上的文件)
打开光驱,5秒后再自动关闭光驱的程序:
#include <fcntl.h>
#include <linux/cdrom.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
int main(void)
{
int fd = open("/dev/cdrom", O_RDONLY | O_NONBLOCK);
if (fd == -1)
{
printf("Failed opening CD-ROM.\n");
return -1;
}
if (!ioctl(fd, CDROMEJECT, NULL))
printf("Ejected CD-ROM successfully.\n");
else
printf("Failed ejecting CD-ROM.\n");
sleep(5);
if (!ioctl(fd, CDROMCLOSETRAY, NULL))
printf("Closed CD-ROM successfully.\n");
else
printf("Failed closing CD-ROM.\n");
close(fd);
return 0;
}
[octopus@pc3 cdrom]$ ./cdrom
Ejected CD-ROM successfully.
Closed CD-ROM successfully.
[octopus@pc3 cdrom]$
SUSE无法弹出光驱“device is busy”:http://www.linuxdiyf.com/linux/5719.html