The ioctl system call is an all-purpose interface for controlling hardware devices. The first argument to ioctl is a file descriptor, which should be opened to the device that you want to control. The second argument is a request code that indicates the operation that you want to perform. Various request codes are available for different devices. Depending on the request code, there may be additional arguments supplying data to ioctl.
Many of the available requests codes for various devices are listed in the ioctl_list man page. Using ioctl generally requires a detailed understanding of the device driver corresponding to the hardware device that you want to control. Most of these are quite specialized and are beyond the scope of this book. However, we'll present one example to give you a taste of how ioctl is used.
int main (int argc, char* argv)
/* Open a file descriptor to the device specified on the command line. */
int fd = open (argv, O_RDONLY);
/* Eject the CD-ROM. */
ioctl (fd, CDROMEJECT);
/* Close the file descriptor. */
Listing 6.2 presents a short program that ejects the disk in a CD-ROM drive (if the drive supports this). It takes a single command-line argument, the CD-ROM drive device. It opens a file descriptor to the device and invokes ioctl with the request code CDROMEJECT. This request, defined in the header <linux/cdrom.h>, instructs the device to eject the disk.
For example, if your system has an IDE CD-ROM drive connected as the master device on the secondary IDE controller, the corresponding device is /dev/hdc. To eject the disk from the drive, invoke this line:
% ./cdrom-eject /dev/hdc