Devices file in linux

Regarding Device Files in Linux

As I understand, the Device Files in Linux are nothing but a user interface for users to communicate with the actual device. Is there ANY OTHER use of device files? Also does this mean that if a user does not need to communicate with the real device, we do not need device files? Also they tend to model every real device as either a character or block or network device. Is this true?

2 Answers 2

let’s start with some historic facts:

First of all, it was the start of everything. The world was created on Thursday, January 1st, 1970 at 12:00a.m., UTC, according to the Legend of the Epoch, and thus there’s no (standard) way to count any time before that, because it was simply non-existent ;).

Then, it was the ’70s (actually, the late ’60s, but who cares?), do you remember (I don’t. )? We don’t know what was Ken smoking at the time, but it appears to have been some sort of exotic ink used in the top-secret Bell Labs’ files he has was supposed not have access to. Just an infinitesimal fraction of time before The Creation, he said.

Let everything be a file!

And so it was. On Unix, and its uncountable decendants, (almost) everything is a file, to the point that hell (otherwise known as /dev/null ) is a file.

On the Epoch was born the Kernel. It’s the ultimate monarch whose sole purpose is to allow or deny access to Sacred Data. Ah! And to kill everyone who disboeys him (if you do *(int*)0 = 0 , you’ll get a death penality due to the violation of the Address Space Law: Shall not you read, write, or otherwise access any address outside your address space ).

Now, because everything is a file, devices are files, no? There’s no bad on it (except that showing everyone the fact that block devices are the shame they are is a stupid idea). And, because network resources are something, they’re files, no?

Now, how does the Supreme Monarch handles this? First of all, for normal files, everything works as expected. The filesystem driver gets blocks from the massive-storage-device driver, then reads the superblock, blah, blah.

But, what happens will all the others? I usually think of them as «trap» files. Whenever you read or write to them, the kernel detects this special situation, and calls appropiate fallback functions to «simulate» the effect of reading and writing from a regular file. For /dev/null (hell), for instance, all reads will return End-of-File, and all writes get discarded. In the case of files refering to devices, the call does not go directly to the device, but to the device driver, that is, a part of the kernel responsible for handling an specific hardware piece. Thus, there are no «files to devices», but «files to device drivers with some extra information to differentiate respective devices».

Читайте также:  Линукс установка графической оболочки

This allows special files, such as /dev/random , /dev/zero , et al. To exist through the same interface. Though they’re not «files to devices/device drivers», the user has (almost) no way to differentiate between them, so who cares?

Also does this mean that if a user does not need to communicate with the > real device, we do not need device files?

Ritchie would turn in his grave if he would hear that. Those abstractions allow things such as device drivers and utility programs (such as the one that you use to format your USB drive) to be implemented in user-space (although with root permissions, anyway). From the kernel’s point of view, there’s no «user» as you think of it, but processes that are part of some group, known as a «user», identified by its «user ID».

Also they tend to model every real device as either a character or block or network device. Is this true?

Although in practice it’s true, a device driver is not obligated to export its corresponding devices through special files.

I hope this has led some light on you!

Источник

Device file (Русский)

Состояние перевода: На этой странице представлен перевод статьи Device file. Дата последней синхронизации: 8 января 2022. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.

Специальный файл устройства, или просто файл устройства (англ. special device file) — это один из типов файлов в UNIX-подобной операционной системе. Специальные файлы устройств содержат данные, необходимые операционной системе для взаимодействия с физическими устройствами, такими как диски и дисководы, принтеры и факсы и т. п. Фактически, специальные файлы устройств являются указателями на драйверы устройств, и когда процесс обращается к файлу устройств, он по сути работает с драйвером этого устройства.

В Linux они располагаются в каталоге /dev в соответствии с Filesystem Hierarchy Standard.

В Arch Linux файлами устройств управляет udev.

Блочные устройства

Блочное устройство — это специальный файл, обеспечивающий буферизованный доступ к устройству.

Имена блочных устройств

Начало имени устройства указывает на подсистему ядра, используемую для управления этим блочным устройством.

Читайте также:  Иконки для linux mint mate

Важно: Дескрипторы имени ядра для блочных устройств не являются постоянными и могут меняться при каждой загрузке, стоит избегать их использования в файлах конфигурации.

SCSI

Устройства хранения, такие как жёсткие диски, SSD и флэш-накопители, которые поддерживают команду SCSI (SCSI, SAS, UASP), соединение ATA (PATA, SATA) или USB Mass Storage, обрабатываются драйвером SCSI. Все они имеют одну и ту же схему именования.

Имя этих устройств начинается с sd . Затем следует строчная буква, начиная с a для первого обнаруженного устройства ( sda ), b для второго ( sdb ) и так далее.

  • /dev/sda — устройство a , первое обнаруженное устройство.
  • /dev/sde — устройство e , пятое обнаруженное устройство.

NVMe

Имя устройств хранения, подключенных через NVM Express (NVMe), начинается с nvme . Затем следует порядковый номер контроллера устройства: nvme0 для первого обнаруженного контроллера NVMe, nvme1 для второго и так далее. Далее идет буква «n» и число, начинающееся с 1 , обозначающее устройство на контроллере: nvme0n1 для первого обнаруженного устройства на первом обнаруженном контроллере, nvme0n2 для второго обнаруженного устройства на первом обнаруженном контроллере и так далее.

  • /dev/nvme0n1 — устройство 1 на контроллере 0 , первое обнаруженное устройство на первом обнаруженном контроллере.
  • /dev/nvme2n5 — устройство 5 на контроллере 2 , пятое обнаруженное устройство на третьем обнаруженном контроллере.

MMC

SD-карты, карты MMC и устройства хранения данных eMMC обрабатываются драйвером mmc , и имена этих устройств начинаются с mmcblk . Затем следует порядковый номер устройства: mmcblk0 для первого обнаруженного устройства, mmcblk1 для второго и так далее.

  • /dev/mmcblk0 — устройство 0 , первое обнаруженное устройство.
  • /dev/mmcblk4 — устройство 4 , пятое обнаруженное устройство.

Привод оптических дисков SCSI

Имена приводов оптических дисков, которые подключаются с через интерфейс, поддерживаемый драйвером SCSI, начинаются с sr . Затем следует порядковый номер устройства: sr0 для первого обнаруженного устройства, sr1 для второго и так далее.

Udev также предоставляет /dev/cdrom , который является символической ссылкой на /dev/sr0 . Имя всегда будет cdrom независимо от поддерживаемых приводом типов дисков или вставленного носителя.

  • /dev/sr0 — привод оптических дисков 0 , первый обнаруженный.
  • /dev/sr4 — привод оптических дисков 4 , пятый обнаруженный.
  • /dev/cdrom — символическая ссылка на /dev/sr0 .

virtio-blk

Имена дисков, подключенных к интерфейсу блочного устройства virtio (virtio-blk), начинаются с vd . Затем следует строчная буква, начиная с a для первого обнаруженного устройства ( vda ), b для второго ( vdb ) и так далее.

Примечание: Не путайте virtio-blk с virtio-scsi, который эмулирует контроллер SCSI и, таким образом, следует соглашению об именах SCSI.

  • /dev/vda — устройство a , первое обнаруженное устройство.
  • /dev/vde — устройство e , пятое обнаруженное устройство.

Разделы

Имена разделов представляют собой комбинацию имени устройства диска и номера раздела, присвоенного им в таблице разделов: /dev/устройствораздел . Для дисков, имя устройства которых заканчивается цифрой, имя диска и номер раздела разделяются буквой «p»: /dev/устройствоpраздел .

  • /dev/sda1 — раздел 1 на устройстве /dev/sda .
  • /dev/nvme2n5p3 — раздел 3 на устройстве /dev/nvme2n5 .
  • /dev/mmcblk3p4 — раздел 4 на устройстве /dev/mmcblk3 .
  • /dev/vda1 — раздел 1 на устройстве /dev/vda .
  • /dev/loop0p2 — раздел 2 на устройстве /dev/loop0 .
Читайте также:  How to shutdown linux terminal

Инструменты

lsblk

Пакет util-linux предоставляет утилиту lsblk(8) , которая выводит список блочных устройств, например:

NAME FSTYPE LABEL UUID MOUNTPOINT sda ├─sda1 vfat C4DA-2C4D /boot ├─sda2 swap 5b1564b2-2e2c-452c-bcfa-d1f572ae99f2 [SWAP] └─sda3 ext4 56adc99b-a61e-46af-aab7-a6d07e504652 /

Этот пример показывает только одно доступное устройство ( sda ), которое имеет три раздела (от sda1 до sda3 ), каждый из которых имеет свою файловую систему.

wipefs

wipefs может отображать сигнатуры файловой системы, RAID или таблицы разделов (магические строки) с указанного устройства и стирать их, чтобы сделать невидимыми для libblkid(3) . Он не стирает ни сами файловые системы, ни какие-либо другие данные с устройства.

Смотрите wipefs(8) для получения дополнительной информации.

Например, чтобы стереть все сигнатуры с устройства /dev/sdb и создать резервную копию ~/wipefs-sdb-смещение.bak для каждой сигнатуры:

Псевдоустройства

Эти файлы устройств не соответствуют никакому физическому устройству.

Смотрите также

Источник

Where can the devices.txt file be found in Linux?

I am trying to find the kernel documentation within Linux, in particular the ‘devices.txt’ file which has a list of driver and device major and minor numbers, i will be needing this while using the mknod command for personal use. im not looking for an online version instead im looking for the actual file in debian. If anyone has any idea in which directory i can find this file in please let me know. This is what im looking for looks like: https://github.com/torvalds/linux/blob/master/Documentation/admin-guide/devices.txt

You would need the source tree for whatever Ubuntu kernel you are using: apt-get source linux-image-$(uname -r) . then the file should be there in Documentation/admin-guide . (Oh, I see an answer was posted while i was doing this comment.)

@Qasim if so the one you have linked to is the file. What are you actually trying to achieve, because this sounds like an X-Y problem to me.

Then the file you found and linked to will do just fine. And there’s almost zero reason to know how to use mknod. I think I last used it in Redhat 5.2 — twenty years ago. IMHO it’s absolutely no reason what so ever to know it as a normal user — it’s more useful to know how udevd works.

@Qasim: I f you do not download the kernel source, you will not have the file. The file doesn’t change often, so look at it on-line or do what I said to get it.

Yes, but it’s not where I would start. I would generally start with learning the actual tools, and wen you master those it’s time to learn recovery.

Источник

Оцените статью
Adblock
detector