Search code examples
cmknod

How to construct mknod argument with device major and minor numbers


Lets say I want to create /dev/cosole. With the mknod command I do the following

  mknod -m 666 /dev/console c 5 1

If I want to do in in C code I have to do the following

#include <sys/stat.h>
static inline void (){
    mknod("/dev/console", 0600, __dev_t __dev);
}

How do I create the __dev argumment, documentation says

Create a device file named PATH, with permission and special bits MODE and device number DEV (which can be constructed from major and minor device numbers with the `makedev' macro above).

I know character devices are of the type S_IFCHR. I know /dev/console has major 5 and minor 1. How can I generate the __dev parameter with makedev macro as the documentation suggests. How do I account for whether its a block devices or a character device?


Solution

  • The third argument of mknod() is created using the makedev() macro, and holds the major and minor device numbers. The type of device - if it's a character or block device (The argument is ignored for other file types), in included in the second argument, which is a combination of the permission bits bitwise-or'ed with the type of the file - S_IFCHR for character devices, or S_IFBLK for block devices (It can also be used to make regular files, FIFOs and unix sockets, but those are more commonly created using other functions like open(), creat(), mkfifo(), bind(), etc.). So you'd do something like

    int status = mknod("/path/to/my/new/console", S_IFCHR | S_IRUSR | S_IWUSR, makedev(5, 1));