views:

530

answers:

4

How to write char device drivers in Linux?

+2  A: 

Read this book: Linux Device Drivers published by O'Reilly.

Helped me a lot.

HTH, flokra

flokra
+1  A: 

My favorite book for learning how the kernel works, BY FAR (and I've read most of them) is:

Linux Kernel Development (2nd Edition)

This book is fairly short, read it first, then read the O'Reilly book on drivers.

dicroce
+1  A: 

Have a look at some of the really simple standard ones - "null", "zero", "mem", "random", etc, in the standard kernel. They show the simple implementation.

Obviously if you're driving real hardware it's more complicated- you need to understand how to interface with the hardware as well as the subsystem APIs (PCI, USB etc) for your device. You might need to understand how to use interrupts, kernel timers etc as well.

MarkR
+1  A: 

A very good example is the Linux "softdog", or software watchdog timer. When loaded, it will watch a special device for writes and take action depending on the frequency of those writes.

It also shows you how to implement a rudamentary ioctl interface, which is very useful.

The file to look at is drivers/watchdog/softdog.c

If you learn by example, that is a very good one to start with. The basic character devices (null, random, etc) as others suggest are also good, but do not adequately demonstrate how you need to implement an ioctl() interface.

A side note, I believe the driver was written by Alan Cox. If your going to learn from example, its never a bad idea to study the work of a top level maintainer. You can be pretty sure that the driver also illustrates adhering to proper Linux standards.

As far as drivers go (in Linux), character drivers are the easiest to write and also the most rewarding, as you can see your code working very quickly. Good luck and happy hacking.

Tim Post