Linux what is inode

What Are Inodes In Linux?

Inode (Index node) is a data structure on the file system that holds all information about a file except its name and actual data. We can call inode as an identity card without a name. When a file creates a new name and inode is assigned to it. There is two way to fill a disk. One way is to fill all segments in the file system other way is to consume all inode index numbers. Detaching names from inode gives file systems the ability to hard link which means using the same data for multiple files with a different name.

Information Stored In Inode

Below information is stored in the inode and each inode is numbered with a unique number in the file system.

  • File type
  • Permission
  • Owner
  • Group
  • File Size
  • File Access, Deletion and Modification Time
  • Number of Links(soft/hard)
  • Access Control Lists (ACL’s)

List Inode Number

We can list inode number with ls command

  • 1187182 is the inode number of HTML folder

An alternative way to get inode number and file information is stat command

Print inode Information

We can see that the following information is provided by stat command about the output directory.

  • `Size` is the size of the given directory and all content of the directory
  • `Block` is the total block count
  • `IO Block`
  • `Device`
  • `Inode` number is the number of the specified folder
  • `Links` provides total count of links to this folder
  • `Access` part provides rights about this folder from owner, group and others perspective.
  • Owner `Uid`
  • Owner `Guid`
  • `Acces` time
  • `Modify` time
  • `Change` time

Find Files According To Inode

As inodes are base for the file systems they can provide a lot of useful things. One of them is searching according to inode number. Linux find command can search not just file and directory names it can also search and find inode numbers. We will use -inum option in order to search according to the inode number.

Find Files According To Inode

Delete Files With Inode

Another useful case for inode number is deleting files accord to their inode number. This can be especially useful for strange character files we can not type in the terminal. We will use find command again but provide the -delete option in order to remove file.

Источник

Что такое Inode

Inode — это структура данных в которой хранится информация о файле или директории в файловой системе. В файловой системе Linux, например Ext4, у файла есть не только само его содержимое, например, тот текст, но и метаданные, такие как имя, дата создания, доступа, модификации и права. Вот эти метаданные и хранятся в Inode. У каждого файла есть своя уникальная Inode и именно здесь указано в каких блоках находятся данные файла.

Это довольно низкоуровневое понятие, но обычным пользователям приходится взаимодействовать с ним когда эти самые Inode заканчиваются. Возможно вы уже встречались с ошибкой когда место на диске ещё есть, но программа не может создать файл, потому что Inode закончились. В этой статье мы подробно разберемся что такое Inode, а также попытаемся выяснить как избежать связанных с ними проблем.

Что такое Inode в Linux?

Как я уже сказал выше, Inode или I-node или индексный дескриптор — это структура данных, в которой хранятся метаданные файла и перечислены блоки с данными файла. Но начать надо с файловой системы. Файловые системы Ext используют блоки для хранения данных. По умолчанию размер одного блока равен 4092 байта. В начале раздела расположен суперблок, в котором находятся метаданные всей файловой системы, а ним идут несколько зарезервированных блоков, а затем размещена таблица Inode и только после неё блоки с данными. Таким образом, все Inode размещены в начале раздела диска.

Директории — это тоже Inode типа директория, в которых вместо содержимого файла содержится список имён файлов и номера их Inode. Корневая папка в Ext4 имеет номер Inode — 2. Вы можете посмотреть информацию о ней с помощью утилиты debugfs. Утилите в параметрах надо передать диск, на котором расположена файловая система:

sudo debugfs /dev/nvme0n1p5

Затем выполните такую команду:

Здесь указано, что эта Inode имеет тип Directory, права 755. Её владелец и группа root, потому что идентификатор пользователя 0. Чуть ниже расположена информация про время создания, модификации и доступа. А в самом низу находятся блоки с данными этой Inode. Именно там хранится список файлов и папок директории. Вы можете посмотреть содержимое блока командой dump_block:

Читайте также:  Ogg dll windows 10

debugfs: block_dump 9238

Утилита выведет данные в HEX и ASCII формате, и в них будет видно имена папок. Но увидеть номера Inode здесь не получится без дополнительных программ. Проще всего их можно посмотреть с помощью команды ls:

Здесь в первом же столбике находится номер Inode для файла или папки. Для примера можно посмотреть ещё информацию про testfile с номером Inode 1128:

В разделе EXTENTS есть номер блока, в котором находятся данные файла. В данном случае это 6596316. В нём можно посмотреть содержимое файла:

debugfs: block_dump 6596316

Вот так это всё работает на уровне файловой системы. Посмотреть Inode идентификаторы файлов можно также с помощью команды ls. Для этого надо передать ей опцию -i:

Здесь они будут тоже в первой колонке. Обратите внимание, что у каждого файла, папки или символической ссылки уникальный номер Inode. Исключение составляют только жесткие ссылки. Количество Inode в файловой системе ограничено, оно определяется при инициализации файловой системы. Посмотреть текущее количество Inode можно командой tune2fs:

sudo tune2fs -l /dev/nvme0n1p5

Нужная информация находится в поле Inode count. Посмотреть Inode можно с помощью утилиты df передав ей опцию -i:

Как видите, на моём корневом разделе использовано 29% Inode, а блоков у меня уже использовано 95%. Но если бы у меня было очень много мелких файлов, то место бы ещё осталось, а доступные Inode закончились. Тогда бы возникла ошибка создания файла, даже несмотря на то, что место ещё есть. Чтобы избежать такой ситуации надо тщательно планировать как вы будете использовать файловую систему.

Вы не можете изменить количество Inode для существующей файловой системы, зато можете указать для новой с помощью опции -N. Например:

mkfs -t ext4 -N 3000000 /dev/nvme0n1p5

В данном случае будет создана файловая система с тремя миллионами индексов Inode. Ещё можно не указывать точное количество Inode, а указать количество байт в одной Inode, это может быть удобно, если вы знаете средний размер ваших файлов, которые будут хранится в файловой системе. Например:

mkfs -t ext4 -i 2K /dev/nvme0n1p5

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

Выводы

В этой статье мы рассмотрели что такое Inode в Linux, а также что произойдёт если доступное количество Inodes закончатся. Будьте осторожны при создании файловой системы и думайте какие файлы в ней будут размещены и сколько их там будет чтобы избежать проблем с Inode.

Источник

What is inode number in Linux ?

A Linux consider everything a file including hardware devices, printers, directories, and processes. Any text, music, video, image or any multimedia file is considered a regular file. All the regular file contains metadata about the file which describe everything about the file like, type, Inode etc.

An inode is an entry in Inode table, containing information (the metadata) about a regular file and directory. An inode is a data structure on a traditional Unix-style file system such as Ext3 or Ext4.

What is inode number in Linux

Inode number also called index number, it consists following attributes of any file:

  • File types ( executable, block special etc )
  • Permissions ( read, write etc )
  • UID ( Owner )
  • GID ( Group )
  • FileSize
  • Time stamps including last access, last modification and last inode number change.
  • File deletion time
  • Number of links ( soft/hard )
  • Location of ile on harddisk.
  • Some other metadata about file.

Check Inodes on Filesystem

You can find a total number of inodes on disk by using ‘-i‘ option with df command.

The below command shows the total number of Inodes on the file system, uses and free inodes details. In case of inodes full on any filesystem, you can’t create a new file on disk even you have enough free space. So each file system must have free disk and inodes to create file.

Find Inode number of File

To check inode number of file use following command. The first field in output is an inode number of the file.

You can also search file with an inode number using find command. For example:

Inode Changes with Copy, Move and Delete

What happens with inode number when copy, move or delete a file on the filesystem.

Copy file: cp allocates a free inode number and placing a new entry in inode table.

Move or Rename a file: if destination is same filesystem as the source, Has no impact on inode number, it only changes the time stamps in inode table.

Delete a file: Deleting a file in Linux decrements the link count and freeing the inode number to be reused.

Free Inodes on Filesystem

In the case of inodes are full. You need to remove unused files from the filesystem to make Inode free. There is no option to increase/decrease inodes on disk. It only created during the creation of filesystem on any disk.

Источник

Detailed Understanding of Linux Inodes with Example

Linux and other Unix-like Operating systems maintain consistency by treating everything as a file (even the hardware devices). The keyboard, mouse, printers, monitor, hard disk, processes, even the directories are treated as files in Linux. The regular files contain data such as text (text files), music, videos (multimedia files), etc.

Other than regular data, there are some other data about these files, such as their size, ownership, permissions, timestamp etc. This metadata about a file is managed with a data structure known as an inode (index node).

Читайте также:  Remmina linux ������� ��������

What is an inode in Linux?

Every Linux file or directory (from a technical point of view, there’s no real difference between them) has an inode, and this inode contains all of the file’s metadata (ie all the administrative data needed to read a file is stored in its inode).

For example, the inode contains a list of all the blocks in which a file is stored, the owner information for that file, permissions and all other attributes that are set for the file.

Inode limits is per filesystem and is decided at filesystem creation time. The maximum directory size dependent on the filesystem and thus the exact limit differs.

For better performance make your directories smaller by sorting files into subdirectories rather having one large directory.

1. What is an inode number?

Inode number is also known as index number. An inode is a unique number assigned to files and directories while it is created. The inode number will be unique to entire filesystem.

An inode is a data structure on a traditional Unix-style file system such as ext3 or ext4. storing the properties of a file and directories.

Linux extended filesystems such as ext3 or ext4 maintain an array of these inodes called the inode table. This table contains list of all files in that filesystem. The individual inodes in inode table have a unique number (unique to that filesystem) called the inode number.

The following information is stored in inode:

  • File type: regular file, directory, pipe etc.
  • Permissions to that file: read, write, execute
  • Link count: The number of hard link relative to an inode
  • User ID: owner of file
  • Group ID: group owner
  • Size of file: or major/minor number in case of some special files
  • Time stamp: access time, modification time and (inode) change time
  • Attributes: immutable’ for example
  • Access control list: permissions for special users/groups
  • Link to location of file
  • Other metadata about the file

Note that the inode does not store the name of the file but its content only.

2. How to check inode in Linux

If you want to have a look at inodes, on any ext file system you can use below commands to check the properties of the file system and files that are used in it.

a. Display file data information

You can display the inode data on a file or directory by using stat command.

You need to indicate the name of the file as following:

The stat output tells you the various time-stamps of the file, its ownership and permissions, and where it’s stored. The file’s data is kept in the disk block, which is shown in the inode’s stat command output.

You can choose to list only the inode number of a file with the —format option as below:

b. Print index number of files

The ls command is used to list file and directories information. The -i option with ls displays the inode number of each file. We can combine it with -l option to list information in detail

The first column gives the inode number. You can display a particular file’s inode as below:

c. Display filesystem inode space information

By default, df command summarizes available and used disk space. You can instead receive a report on available and used inodes by passing the -i or —inodes option.

This information can be helpful if a partition has very many small files, which can deplete available inodes sooner than they deplete available disk space.

d. List the contents of the filesystem superblock

You can use tune2fs -l command to displays all information related to inode.

e. Manipulate the filesystem meta data

You can see the contents of an inode as it exists on an Ext4 file system with debugfs command. You need to use the stat command that is available in the file system debugger to show the contents of the inode. When done, use exit to close the debugfs environment.

Make sure files on the file system cannot be accessed while working in debugfs. You should consider remounting the file system using mount -o remount /yourfilesystem

You can use debugfs to undelete a file by using its inode and indicating a file

2. Inode structure for directory

As stated above, the directories in Linux are also treated as files. Directory is special file that maps a file name to its inode number (this mapping is called directory entry or dentry). So when we say that a directory contains files and other directories, we mean that this directory is mapping those files and directories (directories are special files, so they also need mapping to their inode numbers) to their inode numbers.

This is the reason why a directory cannot hold two files with same name, because it cannot map one name with two different inode numbers.

As a file is mapped to its inode by its parent directory, then how is top most directory, (i.e. / directory ) mapped to its inode? The inode number of / directory is fixed, and is always 2.

In the output of ls -l , the column following the permissions and before owner is the link count. Link count is the number of hard links to a file. To understand hard links, we begin with links. A link is a pointer to another file.

Читайте также:  Сервер под линукс для windows

In Linux world, two types of links exist:

The symbolic link is a separate file whose contents point to the linked-to file. To create a symbolic link, use the ln command with the option -s . When using the ln command, make sure that you first refer to the name of the original file and then to the name of the link you want to create.

Here ‘filesync’ is a symbolic link to ‘sync.sh’. Think about it as a shortcut. Editing ‘filesync’ is like directly edit the original file but it’s really what happen. If we delete or move the original file, the link will be broken and our ‘filesync’ file will not be longer available.

The ls -l command shows that the resulting file is a symbolic link. This is indicated by the letter l in the first position of the ls -l output and also by the arrow at the end of the listing, which indicates the file the name is referring to.

The contents of a symbolic link are the name of target file only. You can see that the permissions on the symbolic link are completely open. This is because the permissions are not managed

When comparing the symbolic link and the original file, you will notice a clear difference between them.

The original file is just a name that is connected directly to the inode, and the symbolic link refers to the name. The size of the symbolic link is the number of bytes in the name of the file it refers to, because no other information is available in the symbolic link.

To get an idea of what a hard link is, it is important to understand that the identity of a file is its inode number, not its name. A hard link is a name that references an inode. It means that if ‘file1’ has a hard link named ‘file2’, then both of these files refer to same inode. So, when you create a hard link for a file, all you really do is add a new name to an inode.

To do this, use the ln command without option.

Now let’s compare the two files

The interesting thing about hard links is that there is no difference between the original file and the link: they are just two names connected to the same inode.

As you must have noted, unlike soft links, hard links are no special files. Now, link count is the number a file has been hard linked. So a link count increases after creating a hard link as you can see in the above figure. These hard links have two limitations:

  • The directories cannot be hard linked. Linux does not permit this to maintain the acyclic tree structure of directories.
  • A hard link cannot be created across filesystems. Both the files must be on the same filesystems, because different filesystems have different independent inode tables (two files on different filesystems, but with same inode number will be different).

You can retrieve all filename which point to an inode number. It means that you can retrieve hard links because it is the only type of link where we can have some filenames which point to the same content (inode). You can do it with the -inum option of find command as below

With this, you can know which filenames point to the data information so, retrieve all hard link relative to a specific inode number

4. Linux operations with files and its relation with inodes

Most of the operations (such as copy) performed on soft links will affect the actual linked file (with the exception of rm or mv commands, which remove (or move) soft link itself)

Here are some file operations in which inodes play their vital role:

a. copy files

When we copy a file, a new file with a new inode is created.

b. move files

When moving across filesystems, mv command proceeds as cp command above, with the exception that the original file is removed from its location. But when moving within a filesystem, the inode does not change, only the directory mapping of the inode is changed, the actual data on the hard disk (contents of the file) does not move.

Now let’s move the file and check the result

c. remove files

When rm command is issued, first it checks the link count of the file. If the link count is greater than 1 , then it removes that directory entry and decreases the link count. Still, data is present, nor is the inode affected. And when link count is 1 , the inode is deleted from the inode table, inode number becomes free, and the data blocks that this file was occupying are added to the free data block list.

Let’s delete the file and check the result

You can see that the number of inode is decreased.

Conclusion

In this tutorial, we learn what is inode and how to check inode number in Linux. I hope you enjoyed reading and please leave your feedback in the below comment section.

Источник

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