Should Linux character devices terminate read() with newline

742 Views Asked by At

POSIX defines a text file as:

A file that contains characters organized into one or more lines.

POSIX defines a line as

A sequence of zero or more non-newline characters plus a terminating newline character.

Given this, should the read() function of a Linux character device driver append '\n' to the user buffer when it reaches EOF/has no more data?

2

There are 2 best solutions below

0
On BEST ANSWER

Concept of char drivers is analogous to a stream. In this light, read just returns whatever happens to be available next. Now what is available will usually be part of definition of the device whose driver it is. If the device returns newline character then so should the driver. Note that this means the device will return newline on all platforms, not just Linux.

In general, interpretating the bytes returned by read is a matter of higher level abstraction. In terms of policy vs mechanism, char driver can be thought of as providing mechanism, leaving policy to higher layers.

0
On

In classic Unix, the difference between character devices and block devices is that block devices support seek, which implies that they are addressable, in units of fixed sized disk blocks. Character devices do not support seek, they just deliver or accept a stream of characters.

In linux, a device driver is implemented as a struct, containing some flags and parameters plus a collection of function pointers, implementing the methods for read()/write()/etc. Block (disk) drivers will also implement seek(), and maybe even mmap().

Normally, device drivers do not interfere with the actual content being transferred, they only move bytes or blocks to/from the device, using the (hardware) protocol that the device needs (such as manipulating the internal control registers, inspecting status registers, ...)