Creating Null Character device /dev/my_null

Theory:


Connection between the application and the device file is based on the name of the device file. However the connection between the device file and the device driver is based on the number of the device file, not the name.

Important Structures:

struct file_operations:

Defined in : linux/fs.h
Purpose: Holds pointers to functions defined by the driver that performs various operations on the device.

E.g.
struct file_operations fops = {
.read = device_read,
.write = device_write,
.open = device_open,
.release = device_release
};

The above fops structure has defined four function pointers : For reading, writing, opening and closing the device file

struct inode: An inode uniquely identifies a file in a file system. Attributes of an inode are
  • Size
  • Rights
  • Times associated with the file

struct file: Created by kernel on open and is passed to any function that operates on the file, until the last close. After all instances of the file are closed, the kernel releases the data structure. An open file is different from a disk file, represented by struct inode.

Contains many fields:
  • f_mode (Read or Write)
  • f_flags, File opening flags (O_RDONLY, O_NONBLOCK, O_SYNC, O_APPEND, O_TRUNC, etc.)
  • f_op, operations associated with the file
  • private_data, pointer that can be used by the programmer to store device-specific data. The pointer will be initialized to a memory location assigned by the programmer
  • f_pos, the offset within a file.

struct cdev : In kernel, each character device is represented using this structure.

Steps in creating a character driver:

1. Allocate a device number dynamically or statically
2. Initializing the character device with its file operations
3. Registering the character device with Linux Kernel

Code for Null Device which eats everything:




Output:



Notes: 
1. You can refer to the original /dev/null code in drivers/char/mem.c . This same code is for /dev/zero and all other nodes whose major number is 1
2. You can also try to see what happens when you type 'cat /dev/zero > /dev/my_null' (dmesg)

Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

PR, PN and PV Variable in Yocto