Как удалить символические ссылки в linux
Содержание:
- DESCRIPTION top
- COPYRIGHT top
- RATIONALE top
- Creating symlinks to directories
- DESCRIPTION top
- Надёжное удаление данных при утилизации или продаже устройства Anchor link
- NOTES top
- How to use the ln command
- Создание ссылок
- ERRORS top
- Using the link command
- ERRORS top
- COPYRIGHT top
- NOTES top
- DESCRIPTION top
- ERRORS top
- Символические ссылки
DESCRIPTION top
unlink() deletes a name from the filesystem. If that name was the
last link to a file and no processes have the file open, the file is
deleted and the space it was using is made available for reuse.
If the name was the last link to a file but any processes still have
the file open, the file will remain in existence until the last file
descriptor referring to it is closed.
If the name referred to a symbolic link, the link is removed.
If the name referred to a socket, FIFO, or device, the name for it is
removed but processes which have the object open may continue to use
it.
unlinkat()
The unlinkat() system call operates in exactly the same way as either
unlink() or rmdir(2) (depending on whether or not flags includes the
AT_REMOVEDIR flag) except for the differences described here.
If the pathname given in pathname is relative, then it is interpreted
relative to the directory referred to by the file descriptor dirfd
(rather than relative to the current working directory of the calling
process, as is done by unlink() and rmdir(2) for a relative
pathname).
If the pathname given in pathname is relative and dirfd is the
special value AT_FDCWD, then pathname is interpreted relative to the
current working directory of the calling process (like unlink() and
rmdir(2)).
If the pathname given in pathname is absolute, then dirfd is ignored.
flags is a bit mask that can either be specified as 0, or by ORing
together flag values that control the operation of unlinkat().
Currently, only one such flag is defined:
AT_REMOVEDIR
By default, unlinkat() performs the equivalent of unlink() on
pathname. If the AT_REMOVEDIR flag is specified, then
performs the equivalent of rmdir(2) on pathname.
See openat(2) for an explanation of the need for unlinkat().
COPYRIGHT top
Portions of this text are reprinted and reproduced in electronic form
from IEEE Std 1003.1, 2013 Edition, Standard for Information
Technology -- Portable Operating System Interface (POSIX), The Open
Group Base Specifications Issue 7, Copyright (C) 2013 by the
Institute of Electrical and Electronics Engineers, Inc and The Open
Group. (This is POSIX.1-2008 with the 2013 Technical Corrigendum 1
applied.) In the event of any discrepancy between this version and
the original IEEE and The Open Group Standard, the original IEEE and
The Open Group Standard is the referee document. The original
Standard can be obtained online at http://www.unix.org/online.html .
Any typographical or formatting errors that appear in this page are
most likely to have been introduced during the conversion of the
source files to man page format. To report such errors, see
https://www.kernel.org/doc/man-pages/reporting_bugs.html .
IEEE/The Open Group 2013 UNLINK(3P)
Pages that refer to this page:
unistd.h(0p),
cp(1p),
ln(1p),
rm(1p),
rmdir(1p),
unlink(1p),
close(3p),
fstatvfs(3p),
link(3p),
linkat(3p),
posix_fallocate(3p),
remove(3p),
rename(3p),
renameat(3p),
rmdir(3p),
symlink(3p),
symlinkat(3p),
tempnam(3p),
tmpfile(3p),
tmpnam(3p)
RATIONALE top
Unlinking a directory is restricted to the superuser in many
historical implementations for reasons given in link() (see also
rename()).
The meaning of in historical implementations is ``mount point
busy''. Since this volume of POSIX.1‐2008 does not cover the system
administration concepts of mounting and unmounting, the description
of the error was changed to ``resource busy''. (This meaning is used
by some device drivers when a second process tries to open an
exclusive use device.) The wording is also intended to allow
implementations to refuse to remove a directory if it is the root or
current working directory of any process.
The standard developers reviewed TR 24715‐2006 and noted that LSB-
conforming implementations may return instead of
when unlinking a directory. A change to permit this behavior by
changing the requirement for to or was
considered, but decided against since it would break existing
strictly conforming and conforming applications. Applications written
for portability to both POSIX.1‐2008 and the LSB should be prepared
to handle either error code.
The purpose of the unlinkat() function is to remove directory entries
in directories other than the current working directory without
exposure to race conditions. Any part of the path of a file could be
changed in parallel to a call to unlink(), resulting in unspecified
behavior. By opening a file descriptor for the target directory and
using the unlinkat() function it can be guaranteed that the removed
directory entry is located relative to the desired directory.
Creating symlinks to directories
To create a symbolic link to a directory, specify the directory name as the target. For instance, let’s say we have a directory named documents, which contains one file, named file.txt.
Let’s create a symbolic link to documents named dox. This command will do the trick:
ln -s documents/ dox
We now have a symlink named dox which we can refer to as if it is the directory documents. For instance, if we use ls to list the contents of the directory, and then to list the contents of the symlinked directory, they will both show the same file:
ls documents
file.txt
ls dox
file.txt
When we work in the directory dox now, we will actually be working in documents, but we will see the word dox instead of documents in all pathnames.
Symbolic links are a useful way to make shortcuts to long, complicated pathnames. For instance, this command:
ln -s documents/work/budgets/Engineering/2014/April aprbudge
…will save us a lot of typing; now, instead of changing directory with the following command:
cd documents/work/budgets/Engineering/2014/April
…we can do this, instead:
cd aprbudge
Normally, you remove directories (once they’re empty) with the rmdir command. But our symbolic link is not actually a directory: it’s a file that points to a directory. So to remove our symlink, we use the rm command:
rm aprbudge
This will remove the symlink, but the original directory and all its files are not affected.
DESCRIPTION top
symlink() creates a symbolic link named linkpath which contains the
string target.
Symbolic links are interpreted at run time as if the contents of the
link had been substituted into the path being followed to find a file
or directory.
Symbolic links may contain .. path components, which (if used at the
start of the link) refer to the parent directories of that in which
the link resides.
A symbolic link (also known as a soft link) may point to an existing
file or to a nonexistent one; the latter case is known as a dangling
link.
The permissions of a symbolic link are irrelevant; the ownership is
ignored when following the link, but is checked when removal or
renaming of the link is requested and the link is in a directory with
the sticky bit (S_ISVTX) set.
If linkpath exists, it will not be overwritten.
symlinkat()
The symlinkat() system call operates in exactly the same way as
symlink(), except for the differences described here.
If the pathname given in linkpath is relative, then it is interpreted
relative to the directory referred to by the file descriptor newdirfd
(rather than relative to the current working directory of the calling
process, as is done by symlink() for a relative pathname).
If linkpath is relative and newdirfd is the special value AT_FDCWD,
then linkpath is interpreted relative to the current working
directory of the calling process (like symlink()).
If linkpath is absolute, then newdirfd is ignored.
Надёжное удаление данных при утилизации или продаже устройства Anchor link
Если вы захотите выкинуть или продать старое устройство, вы, возможно, захотите убедиться в том, что никто не сможет извлечь из него ваши данные. Исследования неоднократно подтверждали тот факт, что владельцы устройств обычно игнорируют эту угрозу – перепродаются жесткие диски, заполненные конфиденциальной информацией. Таким образом, перед продажей или утилизацией компьютера, сначала убедитесь в том, что вы перезаписали накопители различными данными, не имеющими ценности. Даже если вы не избавляетесь от своего компьютера, которым вы перестали пользоваться, вам лучше затереть данные на жестком диске перед размещением компьютера в чулане. «Darik’s Boot and Nuke» — инструмент, предназначенный специально для этой цели. В сети интернет размещено множество руководств по его использованию (включая это).
Некоторое ПО, обеспечивающее полное шифрование диска, способно уничтожить главный ключ шифрования, что сделает содержимое диска нечитаемым навсегда. Так как ключ являет собой лишь крохотный объем данных, он может быть уничтожен практически мгновенно, а это представляет собой гораздо более быструю альтернативу утилите Darik’s Boot and Nuke, которая будет работать достаточно долго на жестких дисках большой ёмкости. Однако, эта возможность применима лишь к дискам, которые уже были зашифрованы. Если вы заранее не начали пользоваться полным шифрованием диска, то вам придется перезаписывать весь диск посторонними данными перед тем, как избавиться от него.
Избавляемся от CD- или DVD-дисков
Когда заходит речь об утилизации CD-дисков, вам следует сделать то же самое, что вы делаете с бумагой – используйте шредер. Существуют недорогие шредеры, которым по силам и CD-диски. Никогда не выбрасывайте в мусор CD-диски, если на них может быть какая-либо конфиденциальная информация.
Надёжное удаление данных с твердотельных накопителей (SSD дисков), флэшек, и SD карт
К сожалению, в связи с иными принципами работы SSD дисков, флэшек и карт памяти SD, почти невозможно надёжно удалить с них файлы и затереть свободное место. Поэтому лучшим способом защиты конфиденциальных данных остаётся использование шифрования—таким образом, даже если файл останется на диске, он останется нечитаем для тех, кто заполучит этот диск, но не сможет его расшифровать. В настоящее время мы не можем предложить надёжную и унифицированную процедуру, позволяющую безопасно удалить данные с SSD диска. Если вы хотите знать, почему именно это так тяжело осуществить, читайте дальше.
Как было упомянуто ранее, в работе SSD дисков и USB накопителей используется технология под названием нивелирование износа. Работает она следующим образом: пространство для записи на каждом диске разделено на несколько блоков, как страницы в тетради. При записи файла на диск он (файл) присваивается конкретному блоку или группе блоков (страниц). Если вы захотите перезаписать файл, то нужно бы указать диску перезаписать именно эти блоки. Но диски SSD и USB флэшки со временем могут испортить (износить) блоки памяти при удалении и перезаписи данных. Каждый блок может быть записан и затёрт ограниченное количество раз, а затем он выйдет из строя (точно так же, продолжая записывать что-либо карандашом на листе бумаги и стирая эту надпись снова и снова, вы сотрете лист до дыр). Для противодействия этому процессу SSD диски и USB флэшки стараются удерживать количество записей и стираний каждого блока примерно на одном уровне, чтобы накопитель проработал как можно дольше (это и означает нивелирование износа). Побочный эффект данного процесса таков: иногда вместо стирания и перезаписи блока данных, в который файл был записан изначально, диск просто отметит его недействительным и запишет изменённый файл в другой блок данных. Это сродни тому, что вы оставите неизменной надпись на странице и, не стирая старую надпись, начнете писать на новой странице, просто обновив оглавление и указав в нём новую страницу. Все это происходит на очень низком уровне — управляется электронной начинкой самого диска, и операционная система даже не знает, что именно происходит. Это значит, что несмотря на то, что вы попытаетесь перезаписать файл новыми данными, нет никакой гарантии, что диск на самом деле перезапишет его. Именно поэтому надёжное удаление данных с SSD дисков настолько сложно.
NOTES top
Hard links, as created by link(), cannot span filesystems. Use
symlink(2) if this is required.
POSIX.1-2001 says that link() should dereference oldpath if it is a
symbolic link. However, since kernel 2.0, Linux does not do so: if
oldpath is a symbolic link, then newpath is created as a (hard) link
to the same symbolic link file (i.e., newpath becomes a symbolic link
to the same file that oldpath refers to). Some other implementations
behave in the same manner as Linux. POSIX.1-2008 changes the
specification of link(), making it implementation-dependent whether
or not oldpath is dereferenced if it is a symbolic link. For precise
control over the treatment of symbolic links when creating a link,
use linkat().
Glibc notes
On older kernels where linkat() is unavailable, the glibc wrapper
function falls back to the use of link(), unless the
AT_SYMLINK_FOLLOW is specified. When oldpath and newpath are
relative pathnames, glibc constructs pathnames based on the symbolic
links in /proc/self/fd that correspond to the olddirfd and newdirfd
arguments.
How to use the ln command
So the syntax is as follows to create a symbolic link in Unix or Linux, at the shell prompt: For example create a softlink for /webroot/home/httpd/test.com/index.php as /home/vivek/index.php, enter the following command: Sample outputs:
lrwxrwxrwx 1 vivek vivek 16 2007-09-25 22:53 index.php -> /webroot/home/httpd/test.com/index.php
You can now edit the soft link named /home/vivek/index.php and /webroot/home/httpd/test.com/index.php will get updated: Your actual file /webroot/home/httpd/test.com/index.php remains on disk even if you deleted the soft link /home/vivek/index.php using the rm command:
Создание ссылок
Перейдем от теории к практике и поговорим о главной теме статьи — команде ln. Как вы уже знаете, она используется для создания двух типов ссылок. Однако стоит заметить, что некоторые файловые менеджеры имеют встроенную функцию по добавлению символического линка. Для этого нужно щелкнуть ПКМ по файлу или папке и выбрать пункт «Создать ссылку», «Create Link» или «Make Link». Тогда soft link будет помещен в этот же каталог, а вы можете переместить его в любое другое место на накопителе.
Для начала стоит упомянуть дополнительные действия, которые часто становятся полезными при осуществлении различных действий с файлами
Важно знать путь к целевому объекту или уметь его определить. Что касается определения, происходит оно так:
- Запустите файловый менеджер любым удобным методом, например, перейдя в домашнюю папку через значок на рабочем столе.

Здесь отыщите в каталогах необходимый файл или папку, через правый клик мыши выберите пункт «Свойства».

В разделе «Основные» вы найдете расположение родительской папки, добавьте к нему название элемента, чтобы получить полный путь, например, .

Если вы собираетесь создавать несколько линков для файлов из одной директории, советуем перейти к ней через «Терминал». Делается это путем ввода . Такое действие позволит указывать только относительный путь к объекту.

Символическая ссылка
Рассмотрим утилиту ln в действии. Начнем с создания символической ссылки на файл. Для этого воспользуйтесь стандартной консолью и выполните такие действия:
- Впишите , где file — имя или полный путь к файлу или директории, а slink — название ссылки. Она будет помещена в тот же каталог, где и находится целевой объект.

Введите и активируйте , чтобы увидеть информацию по поводу находящихся в каталоге объектов. Символическая ссылка выделена отдельным цветом, а через -> указана ее цель. Как видите, файл и линк имеют разные идентификаторы и права.

Для наглядности удалим целевой элемент через .

После повторного просмотра списка содержимого, вы увидите, что символический линк теперь испорчен и не работает, поскольку целевой объект был удален.

Выше вы могли заметить, что для просмотра содержимого папок использовалась стандартная команда ls
Если есть желание ознакомиться с ее действием более подробно, обратите внимание на наш отдельный материал ниже
Жесткая ссылка
Создание жесткой ссылки во многом похоже с тем типом, который мы рассмотрели выше. Единственное различие заключается в отсутствии опции -s. Тогда вся процедура будет иметь примерно такой вид:
- Введите и активируйте .

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

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

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

Информация будет доступна до тех пор, пока не удалятся все указатели на нее (исходный файл и все жесткие ссылки). Команда cat, используемая в последнем пункте, отвечает за просмотр содержимого файлов. Детальное описание всех ее возможностей ищите в статье далее.
Выше вы были ознакомлены не только со стандартной командой ln, но и узнали о двух типах доступных ссылок на объекты в Linux. Конечно, чаще бывают задействованы символические линки, но жесткие тоже иногда становятся полезными. О других популярных командах в Линукс можете узнать из нашего отдельного материала.
Опишите, что у вас не получилось.
Наши специалисты постараются ответить максимально быстро.
ERRORS top
EACCES Write access to the directory containing newpath is denied, or
search permission is denied for one of the directories in the
path prefix of oldpath or newpath. (See also
path_resolution(7).)
EDQUOT The user's quota of disk blocks on the filesystem has been
exhausted.
EEXIST newpath already exists.
EFAULT oldpath or newpath points outside your accessible address
space.
EIO An I/O error occurred.
ELOOP Too many symbolic links were encountered in resolving oldpath
or newpath.
EMLINK The file referred to by oldpath already has the maximum number
of links to it. For example, on an ext4(5) filesystem that
does not employ the dir_index feature, the limit on the number
of hard links to a file is 65,000; on btrfs(5), the limit is
65,535 links.
ENAMETOOLONG
oldpath or newpath was too long.
ENOENT A directory component in oldpath or newpath does not exist or
is a dangling symbolic link.
ENOMEM Insufficient kernel memory was available.
ENOSPC The device containing the file has no room for the new
directory entry.
ENOTDIR
A component used as a directory in oldpath or newpath is not,
in fact, a directory.
EPERM oldpath is a directory.
EPERM The filesystem containing oldpath and newpath does not support
the creation of hard links.
EPERM (since Linux 3.6)
The caller does not have permission to create a hard link to
this file (see the description of
/proc/sys/fs/protected_hardlinks in proc(5)).
EPERM oldpath is marked immutable or append-only. (See
ioctl_iflags(2).)
EROFS The file is on a read-only filesystem.
EXDEV oldpath and newpath are not on the same mounted filesystem.
(Linux permits a filesystem to be mounted at multiple points,
but link() does not work across different mount points, even
if the same filesystem is mounted on both.)
The following additional errors can occur for linkat():
EBADF olddirfd or newdirfd is not a valid file descriptor.
EINVAL An invalid flag value was specified in flags.
ENOENT AT_EMPTY_PATH was specified in flags, but the caller did not
have the CAP_DAC_READ_SEARCH capability.
ENOENT An attempt was made to link to the /proc/self/fd/NN file
corresponding to a file descriptor created with
open(path, O_TMPFILE | O_EXCL, mode);
See open(2).
ENOENT oldpath is a relative pathname and olddirfd refers to a
directory that has been deleted, or newpath is a relative
pathname and newdirfd refers to a directory that has been
deleted.
ENOTDIR
oldpath is relative and olddirfd is a file descriptor
referring to a file other than a directory; or similar for
newpath and newdirfd
EPERM AT_EMPTY_PATH was specified in flags, oldpath is an empty
string, and olddirfd refers to a directory.
Using the link command
What the link command does is allow us to manually create a link to file data that already exists. So, let’s use link to create our own link to the file data recently created. In essence, we’ll create another file name for the data that already exists.
Let’s call our new link file2.txt. How do we create it?
The general form of the link command is: «link file_name linkname«. Our first argument is the name of the file whose data we’re linking to; the second argument is the name of the new link we’re creating.
link file1.txt file2.txt
Now both file1.txt and file2.txt point to the same data on the disk:
cat file1.txt
This is a file.
cat file2.txt
This is a file.
The important thing to realize is that we did not make a copy of this data. Both file names point to the same bytes of data on the disk. Here’s an illustration to help you visualize it:

If we change the contents of the data pointed to by either one of these files, the other file’s contents are changed as well. Let’s append a line to one of them using the >> operator:
echo "It points to data on the disk." >> file1.txt
Now let’s look at the contents of file1.txt:
cat file1.txt
This is a file. It points to data on the disk.
… and now let’s look at the second file, the one we created with the link command:
cat file2.txt
This is a file. It points to data on the disk.
Both files show the change because they share the same data on the disk. Changes to the data of either one of these files will change the contents of the other.
But what if we delete one of the files? Will both files be deleted?
No. If we delete one of the files, we’re deleting one of the links to the data. Because we created another link manually, we still have a pointer to that data; we still have a way, at the user-level, to access the data we put in there. So if we use the rm command to remove our first file:
rm file1.txt
…it no longer exists as a file with that name:
cat file1.txt
cat: file1.txt: No such file or directory
…but the link to the data we manually created still exists, and still points to the data:
cat file2.txt
This is a file. It points to data on the disk.
As you can see, the data stays on the disk even after the «file» (which is actually a link to the data) is removed. We can still access that data as long as there is a link to it. This is important to know when you’re removing files — «removing» a file makes the data inaccessible by unlink-ing it. The data still exists on the storage media, somewhere, inaccessible to the system, and that space on disk is marked as being available for future use.
The type of link we’ve been working with here is sometimes called a «hard» link. A hard link and the data it links to must always exist on the same filesystem; you can’t, for instance, create a hard link on one partition to file data stored on another partition. You also can’t create a hard link to a directory. Only symbolic links may link to a directory; we’ll get to that in a moment.
ERRORS top
EACCES Write access to the directory containing pathname is not
allowed for the process's effective UID, or one of the
directories in pathname did not allow search permission. (See
also path_resolution(7).)
EBUSY The file pathname cannot be unlinked because it is being used
by the system or another process; for example, it is a mount
point or the NFS client software created it to represent an
active but otherwise nameless inode ("NFS silly renamed").
EFAULT pathname points outside your accessible address space.
EIO An I/O error occurred.
EISDIR pathname refers to a directory. (This is the non-POSIX value
returned by Linux since 2.1.132.)
ELOOP Too many symbolic links were encountered in translating
pathname.
ENAMETOOLONG
pathname was too long.
ENOENT A component in pathname does not exist or is a dangling
symbolic link, or pathname is empty.
ENOMEM Insufficient kernel memory was available.
ENOTDIR
A component used as a directory in pathname is not, in fact, a
directory.
EPERM The system does not allow unlinking of directories, or
unlinking of directories requires privileges that the calling
process doesn't have. (This is the POSIX prescribed error
return; as noted above, Linux returns EISDIR for this case.)
EPERM (Linux only)
The filesystem does not allow unlinking of files.
EPERM or EACCES
The directory containing pathname has the sticky bit (S_ISVTX)
set and the process's effective UID is neither the UID of the
file to be deleted nor that of the directory containing it,
and the process is not privileged (Linux: does not have the
CAP_FOWNER capability).
EPERM The file to be unlinked is marked immutable or append-only.
(See ioctl_iflags(2).)
EROFS pathname refers to a file on a read-only filesystem.
The same errors that occur for unlink() and rmdir(2) can also occur
for unlinkat(). The following additional errors can occur for
unlinkat():
EBADF dirfd is not a valid file descriptor.
EINVAL An invalid flag value was specified in flags.
EISDIR pathname refers to a directory, and AT_REMOVEDIR was not
specified in flags.
ENOTDIR
pathname is relative and dirfd is a file descriptor referring
to a file other than a directory.
COPYRIGHT top
Portions of this text are reprinted and reproduced in electronic form
from IEEE Std 1003.1, 2013 Edition, Standard for Information
Technology -- Portable Operating System Interface (POSIX), The Open
Group Base Specifications Issue 7, Copyright (C) 2013 by the
Institute of Electrical and Electronics Engineers, Inc and The Open
Group. (This is POSIX.1-2008 with the 2013 Technical Corrigendum 1
applied.) In the event of any discrepancy between this version and
the original IEEE and The Open Group Standard, the original IEEE and
The Open Group Standard is the referee document. The original
Standard can be obtained online at http://www.unix.org/online.html .
Any typographical or formatting errors that appear in this page are
most likely to have been introduced during the conversion of the
source files to man page format. To report such errors, see
https://www.kernel.org/doc/man-pages/reporting_bugs.html .
IEEE/The Open Group 2013 UNLINK(1P)
Pages that refer to this page:
link(1p)
NOTES top
Under Linux, these functions make use of the getcwd() system call
(available since Linux 2.1.92). On older systems they would query
/proc/self/cwd. If both system call and proc filesystem are missing,
a generic implementation is called. Only in that case can these
calls fail under Linux with EACCES.
These functions are often used to save the location of the current
working directory for the purpose of returning to it later. Opening
the current directory (".") and calling fchdir(2) to return is
usually a faster and more reliable alternative when sufficiently many
file descriptors are available, especially on platforms other than
Linux.
C library/kernel differences
On Linux, the kernel provides a getcwd() system call, which the
functions described in this page will use if possible. The system
call takes the same arguments as the library function of the same
name, but is limited to returning at most PATH_MAX bytes. (Before
Linux 3.12, the limit on the size of the returned pathname was the
system page size. On many architectures, PATH_MAX and the system
page size are both 4096 bytes, but a few architectures have a larger
page size.) If the length of the pathname of the current working
directory exceeds this limit, then the system call fails with the
error ENAMETOOLONG. In this case, the library functions fall back to
a (slower) alternative implementation that returns the full pathname.
Following a change in Linux 2.6.36, the pathname returned by the
getcwd() system call will be prefixed with the string "(unreachable)"
if the current directory is not below the root directory of the
current process (e.g., because the process set a new filesystem root
using chroot(2) without changing its current directory into the new
root). Such behavior can also be caused by an unprivileged user by
changing the current directory into another mount namespace. When
dealing with pathname from untrusted sources, callers of the
functions described in this page should consider checking whether the
returned pathname starts with '/' or '(' to avoid misinterpreting an
unreachable path as a relative pathname.
DESCRIPTION top
These functions return a null-terminated string containing an
absolute pathname that is the current working directory of the
calling process. The pathname is returned as the function result and
via the argument buf, if present.
The getcwd() function copies an absolute pathname of the current
working directory to the array pointed to by buf, which is of length
size.
If the length of the absolute pathname of the current working
directory, including the terminating null byte, exceeds size bytes,
NULL is returned, and errno is set to ERANGE; an application should
check for this error, and allocate a larger buffer if necessary.
As an extension to the POSIX.1-2001 standard, glibc's getcwd()
allocates the buffer dynamically using malloc(3) if buf is NULL. In
this case, the allocated buffer has the length size unless size is
zero, when buf is allocated as big as necessary. The caller should
free(3) the returned buffer.
get_current_dir_name() will malloc(3) an array big enough to hold the
absolute pathname of the current working directory. If the
environment variable PWD is set, and its value is correct, then that
value will be returned. The caller should free(3) the returned
buffer.
getwd() does not malloc(3) any memory. The buf argument should be a
pointer to an array at least PATH_MAX bytes long. If the length of
the absolute pathname of the current working directory, including the
terminating null byte, exceeds PATH_MAX bytes, NULL is returned, and
errno is set to ENAMETOOLONG. (Note that on some systems, PATH_MAX
may not be a compile-time constant; furthermore, its value may depend
on the filesystem, see pathconf(3).) For portability and security
reasons, use of getwd() is deprecated.
ERRORS top
On failure, errno is set to indicate the cause of the error. Values
which may appear in errno include the following:
EACCES Permission to shm_unlink() the shared memory object was
denied.
EACCES Permission was denied to shm_open() name in the specified
mode, or O_TRUNC was specified and the caller does not have
write permission on the object.
EEXIST Both O_CREAT and O_EXCL were specified to shm_open() and the
shared memory object specified by name already exists.
EINVAL The name argument to shm_open() was invalid.
EMFILE The per-process limit on the number of open file descriptors
has been reached.
ENAMETOOLONG
The length of name exceeds PATH_MAX.
ENFILE The system-wide limit on the total number of open files has
been reached.
ENOENT An attempt was made to shm_open() a name that did not exist,
and O_CREAT was not specified.
ENOENT An attempt was to made to shm_unlink() a name that does not
exist.
Символические ссылки
Символические ссылки более всего похожи на обычные ярлыки. Они содержат адрес нужного файла в вашей файловой системе. Когда вы пытаетесь открыть такую ссылку, то открывается целевой файл или папка. Главное ее отличие от жестких ссылок в том, что при удалении целевого файла ссылка останется, но она будет указывать в никуда, поскольку файла на самом деле больше нет.
Вот основные особенности символических ссылок:
- Могут ссылаться на файлы и каталоги;
- После удаления, перемещения или переименования файла становятся недействительными;
- Права доступа и номер inode отличаются от исходного файла;
- При изменении прав доступа для исходного файла, права на ссылку останутся неизменными;
- Можно ссылаться на другие разделы диска;
- Содержат только имя файла, а не его содержимое.
Теперь давайте рассмотрим жесткие ссылки.






