what is the meaning of this macro _IOR(MY_MACIG, 0, int)?

Rafal picture Rafal · Mar 19, 2014 · Viewed 24.9k times · Source

i was going through ioctl sample programs to check how it communicates with kernel space. in program WRITE_IOCTL is used as command

#define WRITE_IOCTL _IOW(MY_MACIG, 1, int)
ioctl(fd, WRITE_IOCTL, "hello world")

I am not able to understand what is _IOW(MY_MACIG, 1, int). here is the link from where i downloaded the program. please help me. http://people.ee.ethz.ch/~arkeller/linux/multi/kernel_user_space_howto-4.html

Answer

Ayman Khamouma picture Ayman Khamouma · Mar 26, 2014

As you may know, an ioctl should be unique, as explained in the Linux Device Drivers book:

The ioctl command numbers should be unique across the system in order to prevent errors caused by issuing the right command to the wrong device.Such a mismatch is not unlikely to happen, and a program might find itself trying to change the baudrate of a non-serial-port input stream, such as a FIFO or an audio device. If each ioctl number is unique, the application gets an EINVAL error rather than succeeding in doing something unintended.

Furthermore, an ioctl can require to write data to and/or read data from kernel space.

When one creates it's own driver that performs ioctls, he will need to describe all this in the ioctl command.

_IO, _IOW, _IOR, _IORW are helper macros to create a unique ioctl identifier and add the required R/W needed features (direction).

These can take the following params: magic number, the command id, and the data type that will be passed (if any)

The magic number is a unique number that will allow the driver to detect errors such as the one mentioned in the LDD book's quote.

The command id, is a way for your dirver to understand what command is needed to be called.

Last parameter (the type) will allow the kernel to understand the size to be copied.

hope this helps.

PS: you can have more details in Linux Device Drivers book (chapter 6) https://lwn.net/images/pdf/LDD3/ch06.pdf