Сколько раз осуществляется доступ к диску?

Формат соответствует ASN.1. , содержащий последовательность (30) длины 0x86 (80 86), содержащую целое число (02) длины 0x80 (81 80), за которым следует целое число (02) длины 1 (01). Это подходящий открытый ключ RSA.

Предполагая, что ключ SSH находится в файле id_rsa.pub, вы можете преобразовать его в нужный формат с помощью

ssh-keygen -f /dev/stdin -e -m PKCS8 -f id_rsa.pub |
openssl pkey -pubin -outform DER |
od -t x1 -An -w4 |
tr 'a-f' 'A-F' |
tr -d ' ' |
fmt -w 54

(Почему так сложно? Потому что)

.

1
30.07.2018, 05:39
2 ответа

Фон

Скажем, у нас есть следующая настройка каталога:

$ ll
total 0
-rw-r--r-- 2 root root 0 Jul 29 23:36 afile.txt
-rw-r--r-- 2 root root 0 Jul 29 23:36 hL
lrwxrwxrwx 1 root root 9 Jul 30 01:22 sL -> afile.txt

Теперь давайте посмотрим на два ваших вопроса.


Вопросы

  1. If a hard link /hL is given, pointing to the inode of the above file, in what order is the disk accessed?

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

Например:

$ stat hL | head -3
  File: ‘hL’
  Size: 0           Blocks: 0          IO Block: 4096   regular empty file
Device: fd00h/64768d    Inode: 667668      Links: 2

против

$ stat afile.txt | head -3
  File: ‘afile.txt’
  Size: 0           Blocks: 0          IO Block: 4096   regular empty file
Device: fd00h/64768d    Inode: 667668      Links: 2

Единственная разница между этими двумя — название.Таким образом, любой путь потребует одинакового количества обращений к жесткому диску.

  1. If a soft link /sL is given, pointing to the above file, in what order is the disk accessed?

Однако с программными ссылками имеется дополнительный доступ к жесткому диску. Этот дополнительный доступ будет противоречить метаданным каталога, в котором находится файл sL. Затем это вернет сведения о том, что этот файл на самом деле является символической ссылкой и указывает на другой файл/каталог.

Например:

$ stat sL | head -3
  File: ‘sL’ -> ‘afile.txt’
  Size: 9           Blocks: 0          IO Block: 4096   symbolic link
Device: fd00h/64768d    Inode: 681295      Links: 1

Здесь мы можем видеть, что она имеет тип «символическая ссылка» и указывает на afile.txt. Также обратите внимание, что у него разные индексы (681295 и 667668 ), еще одно доказательство того, что это потребует дополнительного чтения.

Итак, каков порядок чтения?

Если вы используете straceдля самой оболочки Bash, где вы запускаете команды для этих файлов/каталогов, вы можете получить представление о том, как все работает.

[pid 18098] stat("/tmp/adir/hL", {st_mode=S_IFREG|0644, st_size=0,...}) = 0
[pid 18098] open("/tmp/adir/hL", O_RDONLY) = 3
[pid 18098] fstat(3, {st_mode=S_IFREG|0644, st_size=0,...}) = 0

Вот вывод команды more /tmp/adir/hL.

Для/tmp/adir/hL:

  • стат/откр (/ )→ стат/откр (tmp )→ стат/откр (adir )→ стат/откр (hL)

Для/tmp/adir/sL:

  • стат/откр (/ )→ стат/откр (tmp )→ стат/откр (adir )→ стат/откр (sL )→ стат/откр (файл.txt)

Дополнительная информация

Страница Википедии о символических ссылках также ускользает от всего этого:

Although storing the link value inside the inode saves a disk block and a disk read, the operating system still needs to parse the path name in the link, which always requires reading additional inodes and generally requires reading other, and potentially many, directories, processing both the list of files and the inodes of each of them until it finds a match with the link's path components. Only when a link points to a file in the same directory do "fast symlinks" provide significantly better performance than other symlinks.

Ссылки

1
27.01.2020, 23:31

Оба заданных вопроса на самом деле являются вопросом :«Как path_resolutionработает?», так что просто посмотрите на весь процесс с этой точки зрения.

Из ПУТЬ _РАЗРЕШЕНИЕ (7)читаем:

A filename (or pathname) is resolved as follows.

И после этого мы видим, что первый шаг является общим как для жестких ссылок, так и для символических ссылок (, где система решает, что является начальной точкой разрешения пути :корневой каталог /, chrooted каталог или текущий каталог ).

If the pathname starts with the '/' character, the starting lookup directory is the root directory of the calling process. (A process inherits its root directory from its parent. Usually this will be the root directory of the file hierarchy. A process may get a different root directory by use of the chroot(2) system call. A process may get an entirely private mount namespace in case it—or one of its ancestors—was started by an invocation of the clone(2) system call that had the CLONE_NEWNS flag set.) This handles the '/' part of the pathname.

If the pathname does not start with the '/' character, the starting lookup directory of the resolution process is the current working directory of the process. (This is also inherited from the parent. It can be changed by use of the chdir(2) system call.)

Pathnames starting with a '/' character are called absolute pathnames. Pathnames not starting with a '/' are called relative pathnames.

Поскольку мы не видим никакой разницы в начальной точке между жесткими -и симлинками. Но разница появляется на следующем шаге, когда начинается ходьба по пути :

.

Set the current lookup directory to the starting lookup directory. Now, for each nonfinal component of the pathname, where a component is a substring delimited by '/' characters, this component is looked up in the current lookup directory.

If the process does not have search permission on the current lookup directory, an EACCES error is returned ("Permission denied").

If the component is not found, an ENOENT error is returned ("No such file or directory"). If the component is found, but is neither a directory nor a symbolic link, an ENOTDIR error is returned ("Not a directory").

If the component is found and is a directory, we set the current lookup directory to that directory, and go to the next component.

Как видно из описания, нет разницы в разрешении путей для файлов и жестких ссылок -, процесс одинаков. А как насчет симлинков? Читаем далее:

If the component is found and is a symbolic link (symlink), we first resolve this symbolic link (with the current lookup directory as starting lookup directory). Upon error, that error is returned. If the result is not a directory, an ENOTDIR error is returned. If the resolution of the symlink is successful and returns a directory, we set the current lookup directory to that directory, and go to the next component. Note that the resolution process here can involve recursion if the prefix ('dirname') component of a pathname contains a filename that is a symbolic link that resolves to a directory (where the prefix component of that directory may contain a symbolic link, and so on). In order to protect the kernel against stack overflow, and also to protect against denial of service, there are limits on the maximum recursion depth, and on the maximum number of symbolic links followed. An ELOOP error is returned when the maximum is exceeded ("Too many levels of symbolic links").

Как указано выше, разрешение симлинков требует дополнительных операций доступа к диску, поэтому ответ на оба вопроса:

If a hard link /hL is given, pointing to the inode of the above file, in what order is the disk accessed?

и

If a soft link /sL is given, pointing to the above file, in what order is the disk accessed?

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

Дополнительные показания:

1
27.01.2020, 23:31

Теги

Похожие вопросы