14

I'm trying to clarify which is the most useful (in terms of functionality) method of interacting with devices in Linux. As I understand, device files expose only part of functionality (address blocks in block devices, streams in character devices, etc...). ioctl(2) seems to be most commonly used, yet some people says it's not safe, and so on.

Some good articles or other relevant pointers would be welcome.

9

ioctl tends to go hand-in-hand with a /dev entry; your typical code would do

fd=open("/dev/mydevice",O_RDRW);
ioctl(fd,.....);

This is perfectly standard Unix behaviour. Inside the kernel driver you can put access controls (eg only root can do some things, or require a specific capability for more fine grained access) which makes it pretty flexible and powerful.

Of course this means that devices can expose a lot more than use block/character read-write activity; many things can be done via ioctl calls. Not so easy to use from shell scripts, but pretty easy from C or perl or python or similar.

sysfs entries are another way of interacting with drivers. Typically each type of command would have a different entry, so it can be complicated to write the driver but it makes it very easy to access via userspace; simple shell scripts can manipulate lots of stuff, but may not be very efficient

netlink is primarily focused (I think!) on network data transfers, but it could be used for other stuff. It's really good for larger volumes of data transfer and is meant to be a successor to ioctl in some cases.

All the options are good; your use case may better determine which type of interface to expose from your driver.

2
  • 2
    Adding more to confuse :" ioctl : However, ioctl is deprecated in the kernel, and you will find it hard to get any drivers with new uses of ioctl accepted upstream. The kernel maintainers dislike ioctl because it makes kernel code and application code too interdependent, and it is hard to keep both of them in step across kernel versions and architectures." [Page 255]"Mastering Embedded Linux Programming" by Chris Simmonds [2017]. – Israr Jan 11 '20 at 7:34
  • This appends a question : Then Can we access sysfs from C ? – Israr Jan 11 '20 at 7:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.