How does /dev/zero return a constant stream of zero?

132 Views Asked by At

I am trying to recreate what /dev/zero does. I got a /dev/null driver working more or less, but can not quite see how to implement zero. My main problem is with understanding the "read" part.

The man page says: Reads from /dev/zero always return containing zero ('\0' characters).

Now the driver in drivers/char/mem.c shows the following function:

static ssize_t read_zero(struct file *file, char __user *buf,
         size_t count, loff_t *ppos)`
{
    size_t cleared = 0;
    
    while (count) {
        size_t chunk = min_t(size_t, count, PAGE_SIZE);
        size_t left;
    
        left = clear_user(buf + cleared, chunk);
        if (unlikely(left)) {
            cleared += (chunk - left);
            if (!cleared)
                return -EFAULT;
            break;
        }
        cleared += chunk;
        count -= chunk;
    
        if (signal_pending(current))
            break;
        cond_resched();
    }
    
    return cleared;
}

The manuals for clear_user read: clear_user - Zero a block of memory in user space. I guess this is where the magic happens. So is reading zero "as easy" as to just write 0 to the userspace at *buf?

If not i guess my main question is: how do i force a driver to return \0 when reading from the corresponding file?

0

There are 0 best solutions below