심볼릭 링크와 하드 링크의 차이점은 무엇입니까?
최근에 면접에서이 질문을 받았습니다. 나는 정직했고, 심볼릭 링크가 어떻게 동작하는지, 어떻게 만드는지 알고 있지만 하드 링크의 사용과 그것이 심볼릭 링크와 어떻게 다른지 이해하지 못한다고 말했습니다.
파일 시스템 아래 파일은 inode로 표시됩니다 (또는 여러 inode가 확실하지 않음).
파일 시스템의 파일은 기본적으로 inode에 대한 링크입니다.
그런 다음 하드 링크는 동일한 기본 inode에 대한 링크가있는 다른 파일을 만듭니다.
파일을 삭제하면 기본 inode에 대한 하나의 링크가 제거됩니다. inode는 inode에 대한 모든 링크가 삭제 된 경우에만 삭제됩니다 (또는 삭제 가능 / 덮어 쓰기 가능).
심볼릭 링크는 파일 시스템의 다른 이름에 대한 링크입니다.
하드 링크가 만들어지면 링크는 inode로 연결됩니다. 이름 바꾸기를 삭제하거나 원본 파일을 이동해도 기본 inode에 연결되므로 하드 링크에 영향을주지 않습니다. inode의 데이터 변경 사항은 해당 inode를 참조하는 모든 파일에 반영됩니다.
참고 : 하드 링크는 동일한 파일 시스템 내에서만 유효합니다. 심볼릭 링크는 단순히 다른 파일의 이름이므로 파일 시스템에 걸쳐있을 수 있습니다.
Linux (ish) 콘솔을 사용하면 도움이 될만한 멋진 직관이 있습니다.
두 개의 파일을 만듭니다.
$ touch foo; touch bar
일부 데이터를 입력하십시오.
$ echo "Cat" > foo
$ echo "Dog" > bar
(사실, 파일이 존재하지 않는 경우 파일을 생성하기 때문에 처음부터 echo를 사용할 수 있었지만 ... 신경 쓰지 마세요.)
그리고 예상대로 :
$cat foo; cat bar
Cat
Dog
하드 및 소프트 링크를 만들어 보겠습니다.
$ ln foo foo-hard
$ ln -s bar bar-soft
방금 무슨 일이 일어 났는지 봅시다 :
$ ls -l
foo
foo-hard
bar
bar-soft -> bar
foo의 이름을 변경하는 것은 중요하지 않습니다.
$ mv foo foo-new
$ cat foo-hard
Cat
foo-hard는 변경되지 않은 파일의 내용 인 inode를 가리 킵니다.
$ mv bar bar-new
$ ls bar-soft
bar-soft
$ cat bar-soft
cat: bar-soft: No such file or directory
소프트 링크가 내용이 아닌 변경된 이름을 가리 키기 때문에 파일 내용을 찾을 수 없습니다.
마찬가지로 If foo
가 삭제되면 foo-hard
여전히 내용이 유지 됩니다 . 경우 bar
삭제, bar-soft
존재하지 않는 파일로 바로 링크입니다.
속담처럼 그림은 천 단어의 가치가 있습니다. 이를 시각화하는 방법은 다음과 같습니다.
그 그림을 얻는 방법은 다음과 같습니다.
myfile.txt
새 inode를 가리키는 파일 시스템에 이름 을 만듭니다 ( 파일에 대한 메타 데이터를 포함하고 그 내용을 포함하는 데이터 블록을 가리 킵니다 (예 : "Hello, World!"텍스트).$ echo 'Hello, World!' > myfile.txt
my-hard-link
파일에 대한 하드 링크 를 만듭니다.myfile.txt
이는 "myfile.txt
가리키는 동일한 inode를 가리키는 파일을 만듭니다"를 의미합니다 .$ ln myfile.txt my-hard-link
my-soft-link
파일에 대한 소프트 링크 를 만듭니다.myfile.txt
이는 "파일을 가리켜 야하는 파일 만들기"를 의미합니다myfile.txt
.$ ln -s myfile.txt my-soft-link
myfile.txt
가 삭제 (또는 이동) 되면 어떻게 될지보십시오 . my-hard-link
여전히 동일한 내용을 가리키고 있으므로 영향을받지 않지만 my-soft-link
이제는 아무것도 가리 키지 않습니다. 다른 답변은 각각의 장단점에 대해 설명합니다.
하드 링크는 원본 파일이 이동할 때 유용합니다. 예를 들어, 파일을 / bin에서 / usr / bin 또는 / usr / local / bin으로 이동합니다. / bin에있는 파일에 대한 모든 심볼릭 링크는 이로 인해 끊어 질 수 있지만 파일의 inode에 직접 연결되는 하드 링크는 신경 쓰지 않습니다.
하드 링크는 디렉토리 항목 만 차지하므로 디스크 공간을 덜 차지할 수 있지만 심볼릭 링크는 가리키는 이름을 저장하기 위해 자체 inode가 필요합니다.
하드 링크는 해결하는 데 시간이 덜 걸립니다. 심볼릭 링크는 심볼릭 링크 된 디렉토리에있는 다른 심볼릭 링크를 가리킬 수 있습니다. 그리고 이들 중 일부는 NFS 또는 기타 대기 시간이 긴 파일 시스템에있을 수 있으므로 해결해야 할 네트워크 트래픽이 발생할 수 있습니다. 항상 동일한 파일 시스템에있는 하드 링크는 항상 단일 조회로 확인되며 네트워크 대기 시간을 포함하지 않습니다 (NFS 파일 시스템의 하드 링크 인 경우 NFS 서버가 확인을 수행하고 클라이언트 시스템). 때때로 이것은 중요합니다. 저에게는 아니지만 이것이 중요한 고성능 시스템을 상상할 수 있습니다.
또한 mmap (2) 및 open (2)과 같은 것들은 파일의 inode를 활성 상태로 유지하기 위해 hardlink와 동일한 기능을 사용하므로 파일이 unlink (2) 되더라도 inode는 프로세스가 계속 액세스 할 수 있도록 유지됩니다. 프로세스가 닫히면 파일이 실제로 사라집니다. 이것은 훨씬 더 안전한 임시 파일을 허용합니다 (만약 당신이 읽고 쓸 수있는 곳에 POSIX API가있을 수 있고, 내가 기억하지 못하는 POSIX API가있을 수 있습니다.) 누구도 액세스 할 수없는 데이터입니다. / proc이 모든 사람에게 파일 설명자를 볼 수있는 기능을 부여하기 전에는 사실 이었지만, 이는 또 다른 이야기입니다.
말하자면, 프로세스 A에서 열려 있지만 파일 시스템에서 링크되지 않은 파일을 복구하는 것은 하드 링크를 사용하여 inode 링크를 다시 생성하여 파일을 열어 놓은 프로세스가 파일을 닫거나 사라질 때 파일이 사라지지 않도록하는 것입니다.
하드 링크와 심볼릭 링크의 차이점을 확인하는 간단한 방법은 간단한 예를 사용하는 것입니다. 파일에 대한 하드 링크는 파일이 저장된 위치 또는 해당 파일의 inode를 가리 킵니다. 심볼릭 링크는 실제 파일 자체를 가리 킵니다.
따라서 "a"라는 파일이 있고 하드 링크 "b"와 파일 "a"를 참조하는 심볼릭 링크 "c"를 생성하면 다음과 같습니다.
echo "111" > a
ln a b
ln -s a c
"a", "b"및 "c"의 출력은 다음과 같습니다.
cat a --> 111
cat b --> 111
cat c --> 111
이제 파일 "a"를 제거하고 "a", "b"및 "c"의 출력이 어떻게되는지 살펴 보겠습니다.
rm a
cat a --> No such file or directory
cat b --> 111
cat c --> No such file or directory
그래서 무슨 일이 있었나요?
파일 "c"가 파일 "a"자체를 가리 키기 때문에 파일 "a"가 삭제되면 파일 "c"는 가리킬 것이 없으며 실제로 파일도 삭제됩니다.
그러나 파일 "b"는 파일 "a"의 저장 위치 또는 inode를 가리 킵니다. 따라서 파일 "a"가 삭제되면 더 이상 inode를 가리 키지 않지만 파일 "b"가 수행하기 때문에 inode는 더 이상 하드 링크가 더 이상 가리 키지 않을 때까지 "a"에 속한 모든 내용을 계속 저장합니다.
소프트 링크 :
soft 또는 symbolic은 원본 파일에 대한 바로 가기에 가깝습니다. 원본을 삭제하면 바로 가기가 실패하고 바로 가기 만 삭제하면 원본에는 아무 일도 일어나지 않습니다.
소프트 링크 구문 :ln -s Pathof_Target_file link
출력 : link -> ./Target_file
증명 : readlink link
또한에 ls -l link
출력 당신이 첫 글자가 나타납니다 lrwxrwxrwx
같은 리터 파일이 소프트 링크임을 표시입니다.
링크 삭제 : unlink link
참고 : 원하는 경우 현재 디렉터리에서 다른 위치로 이동 한 후에도 소프트 링크가 작동 할 수 있습니다. 소프트 링크를 만드는 동안 상대 경로가 아닌 절대 경로를 제공해야합니다. 즉 (./Target_file이 아닌 / root / user / Target_file에서 시작)
하드 링크 :
하드 링크는 동일한 파일에 대한 미러 사본 또는 다중 경로에 가깝습니다. file1에 뭔가를하면 파일 2에 나타납니다. 하나를 삭제해도 다른 하나는 계속 유지됩니다.
inode (또는 파일)는 모든 (하드) 링크 또는 (동일한 파일) inode의 모든 경로가 삭제 된 경우에만 삭제됩니다.
하드 링크가 만들어지면 링크에는 원본 파일의 inode가 있습니다. 이름 바꾸기를 삭제하거나 원본 파일을 이동해도 기본 inode에 연결되므로 하드 링크에 영향을주지 않습니다. inode의 데이터 변경 사항은 해당 inode를 참조하는 모든 파일에 반영됩니다.
하드 링크 구문 :ln Target_file link
출력 : 이름 링크가있는 파일이 Targetfile과 동일한 inode 번호로 생성됩니다.
증명 : ls -i link Target_file
(아이 노드 확인)
링크 삭제 : rm -f link
(일반 파일처럼 링크 삭제)
참고 : 심볼릭 링크는 단순히 다른 파일의 이름이므로 파일 시스템에 걸쳐있을 수 있습니다. 하드 링크는 동일한 파일 시스템 내에서만 유효합니다.
심볼릭 링크에는 하드 링크가 누락 된 몇 가지 기능이 있습니다.
- 하드 링크는 파일 콘텐츠를 가리 킵니다. 소프트 링크는 파일 이름을 가리 킵니다.
- 하드 링크의 크기는 콘텐츠의 크기이고 소프트 링크는 파일 이름 크기입니다.
- 하드 링크는 동일한 inode를 공유합니다. 소프트 링크는 그렇지 않습니다.
- 하드 링크는 파일 시스템을 교차 할 수 없습니다. 소프트 링크는 그렇습니다.
심볼릭 링크가 가리키는 위치를 즉시 알 수 있지만 하드 링크를 사용하는 경우 동일한 inode를 공유하는 파일을 찾기 위해 전체 파일 시스템을 탐색해야합니다.
# find / -inum 517333
/home/bobbin/sync.sh /root/synchro
하드 링크는 디렉토리를 가리킬 수 없습니다.
하드 링크에는 두 가지 제한이 있습니다.
- 디렉토리는 하드 링크 될 수 없습니다. Linux는 이것이 디렉토리의 비순환 트리 구조를 유지하는 것을 허용하지 않습니다.
- 파일 시스템간에 하드 링크를 만들 수 없습니다. 서로 다른 파일 시스템은 서로 다른 독립 inode 테이블을 갖기 때문에 두 파일 모두 동일한 파일 시스템에 있어야합니다 (다른 파일 시스템에있는 두 개의 파일이지만 동일한 inode 번호를 갖는 것은 서로 다릅니다).
기호 링크는 경로 이름에 링크됩니다. 이것은 시스템의 파일 트리 어디에나있을 수 있으며 링크가 생성 될 때 존재할 필요도 없습니다. 대상 경로는 상대적이거나 절대적 일 수 있습니다.
하드 링크는 inode에 대한 추가 포인터입니다. 즉, 대상과 동일한 볼륨에만 존재할 수 있습니다. 파일에 대한 추가 하드 링크는 파일을 참조하는 데 사용 된 "원래"이름과 구별 할 수 없습니다.
위키 백과를 알려 드리겠습니다.
몇 가지 사항 :
- 하드 링크와 달리 Symlink는 파일 시스템을 교차 할 수 있습니다 (대부분의 경우).
- Symlink는 디렉토리를 가리킬 수 있습니다.
- 하드 링크는 파일을 가리키며 둘 이상의 이름으로 동일한 파일을 참조 할 수 있습니다.
- 링크가 하나 이상 있으면 데이터를 계속 사용할 수 있습니다.
하드 링크는 증분 백업을 수행 할 때 매우 유용합니다. 예를 들어 rsnapshot을 참조하십시오 . 아이디어는 하드 링크를 사용하여 복사하는 것입니다.
- 백업 번호 n을 n + 1로 복사
- 복사 백업 n-1에서 n
- ...
- 백업 0을 백업 1에 복사
- 변경된 파일로 백업 0을 업데이트합니다.
모든 증분 백업은 변경되지 않은 파일에 대해 동일한 inode 집합을 가리 키기 때문에 새 백업은 변경 사항을 제외하고 추가 공간을 차지하지 않습니다.
Nick의 질문에 덧붙입니다. 하드 링크 는 언제 유용하거나 필요합니까? 내 마음에 떠오르는 유일한 응용 프로그램은 심볼릭 링크가 작업을 수행하지 않는데, chroot 된 환경에서 시스템 파일의 복사본을 제공하는 것입니다.
하드 링크 대 소프트 링크는이 이미지로 쉽게 설명 할 수 있습니다.
또한:
- 하드 링크의 읽기 성능이 기호 링크보다 우수합니다 (마이크로 성능).
- 심볼릭 링크는 복사, 버전 제어, .. 등이 가능합니다. 즉, 실제 파일입니다. 반면에 하드 링크는 약간 낮은 수준에 있으며 심볼릭 링크에 비해 하드 링크를 일반 파일이 아닌 하드 링크로 작업하는 수단을 제공하는 도구가 적다는 것을 알 수 있습니다.
Simply , Hard link : is just add new name to a file, that's mean , a file can have many name in the same time, all name are equal to each other, no one preferred, Hard link is not mean to copy the all contents of file and make new file is not that, it just create an alternative name to be known..
Symbolic link (symlink) : is a file pointer to another file, if the symbolic link points to an existing file which is later deleted, the symbolic link continues to point to the same file name even though the name no longer names any file.
What you think of as an ordinary "file" is actually two separate things: The data of a file, and a directory entry. When you create a hard link for a file, you actually create a second directory entry which refers to the same data. Both directory entries have the exact same functionality; each one can be used to open the file to read it. So you don't really have "a file plus a hard link", you have "file data with two directory entries". What you think of as deleting a file actually deletes a directory entry, and when the last directory entry for the data is deleted, then the data itself is deleted as well. For ordinary files that have only one directory entry, deleting the directory entry will delete the data as always. (While a file is opened, the OS creates a temporary link to the file, so even when you delete all directory entries, the data stays but disappears as soon as you close the file).
As an example, create a file A.txt, a hard link B.txt, and delete A.txt. When you created A.txt, some data was created, and a directory entry A.txt. When you created the hard link, another directory entry B.txt was created, pointing to the exact same data. When you delete A.txt, you still have all the data and a single directory entry B.txt, exactly as if you had create a file B.txt in the first place.
A soft link is just an (almost) ordinary file, except that it doesn't contain data, but the path of another directory entry. If you delete the file that the soft link refers to, then the soft link will contain a path that doesn't point to a directory entry anymore; it is broken. If you delete the soft link, it's like deleting any other file, the file it points to is unaffected.
From MSDN,
Symbolic link
A symbolic link is a file-system object that points to another file system object. The object being pointed to is called the target.
Symbolic links are transparent to users; the links appear as normal files or directories, and can be acted upon by the user or application in exactly the same manner.
Symbolic links are designed to aid in migration and application compatibility with UNIX operating systems. Microsoft has implemented its symbolic links to function just like UNIX links.
Symbolic links can either be absolute or relative links. Absolute links are links that specify each portion of the path name; relative links are determined relative to where relative–link specifiers are in a specified path
An example of Absolute Symbolic Link
X: "C:\alpha\beta\absLink\gamma\file"
Link: "absLink" maps to "\\machineB\share"
Modified Path: "\\machineB\share\gamma\file"
An example of Relative Symbolic Links
X: C:\alpha\beta\link\gamma\file
Link: "link" maps to "..\..\theta"
Modified Path: "C:\alpha\beta\..\..\theta\gamma\file"
Final Path: "C:\theta\gamma\file"
Hard link
A hard link is the file system representation of a file by which more than one path references a single file in the same volume.
To create a hard link in windows, navigate to where link is to be created and enter this command:
mklink /H Link_name target_path
Note that you can delete hard links any order, regardless of the order in which they were created. Also, hard links can not be created when
- references are in different local drives
- references include network drive. In other words, one of the references is a network drive
- hard link to be created is in the same path as the target
Junction
NTFS supports another link type called junction. MSDN defines it as follows:
A junction (also called a soft link) differs from a hard link in that the storage objects it references are separate directories, and a junction can link directories located on different local volumes on the same computer. Otherwise, junctions operate identically to hard links.
The bolded parts in hard link section and junction section show the basic difference between the two.
Command to create a junction in windows, navigate to where link is to be created and then enter:
mklink /J link_name target_path
A directory entry is link a structrue:
struct dentry{
ino_t ino;
char name[256];
}
the ino is the number of inode, the name is the file name, inode structure maybe like:
struct inode{
link_t nlink;
...
}
for example you creat a file /1, the directory entry maybe like:
struct dentry{
ino_t ino; /* such as 15 */
char name[256]; /* "1" */
}
the inode struct maybe like:
struct inode{ /* inode number 15 */
link_t nlink; /* nlink = 1 */
...
}
then you create a hard link(may be /100), the directory entry maybe like:
struct dentry{
ino_t ino; /* 15 */
char name[256]; /* 100 */
}
the inode struct maybe like:
struct inode{ /* inode numebr 15 */
link_t nlink; /* nlink = 2 */
...
}
then you create a symbolic link(may be /200) to file 1, the directory entry maybe like:
struct dentry{
ino_t ino; /* such as 16 */
char name[256]; /* "200" */
}
the inode struct maybe like:
struct inode{ /* inode number 15 */
link_t nlink; /* nlink = 2 */
...
}
struct inode{ /* inode number 16 */
link_t nlink; /* nlink = 1 */
...
} /* the data of inode 16 maybe /1 or 1 */
Adding to all the above answers, the difference in finding the hardlink and softlink file can be understood as below:
I have a file f6
in my current directory, as well as a directory named t2
.
File named f1
and ./t2/f2
are symbolic links to f6
.
File named f7
and ./t2/f8
are hard links of f6
.
To find soft as well as hard link we can use:
$ find -L . -samefile f6
> ./f1
> ./f6
> ./f7
> ./t2/f2
> ./t2/f8
To find only hardlink we can use:
$ find . -xdev -samefile f6
> ./f6
> ./f7
> ./t2/f8
Since hardlinks can be created on the same file system, we can search all the hardlinks without -L
option used (with -xdev
option) in the same file-system/mount-point. It saves the unnecessary search into different mount points.
So searching the hardlink is somewhat faster then searching the softlinks(Please rectify if I am wrong or not clear).
Symbolic links give another name to a file, in a way similar to hard links. But a file can be deleted even if there are remaining symbolic links.
I just found an easy way to understand hard links in a common scenario, software install.
One day I downloaded a software to folder Downloads
for install. After I did sudo make install
, some executables were cp
ed to local bin folder. Here, cp
creates hard link. I was happy with the software but soon realized that Downloads
isn't a good place in the long run. So I mv
ed the software folder to source
directory. Well, I can still run the software as before without worrying about any target link things, like in Windows. This means hard link finds inode directly and other files around.
IN this answer when i say a file i mean the location in memory
All the data that is saved is stored in memory using a data structure called inodes Every inode has a inodenumber.The inode number is used to access the inode.All the hard links to a file may have different names but share the same inode number.Since all the hard links have the same inodenumber(which inturn access the same inode),all of them point to the same physical memory.
A symbolic link is a special kind of file.Since it is also a file it will have a file name and an inode number.As said above the inode number acceses an inode which points to data.Now what makes a symbolic link special is that the inodenumbers in symbolic links access those inodes which point to "a path" to another file.More specifically the inode number in symbolic link acceses those inodes who point to another hard link.
when we are moving,copying,deleting a file in GUI we are playing with the hardlinks of the file not the physical memory.when we delete a file we are deleting the hardlink of the file. we are not wiping out the physical memory.If all the hardlinks to file are deleted then it will not be possible to access the data stored although it may still be present in memory
My two cents on usage:
Soft links may be used to shorten long path names, i.e.:
ln -s /long/folder/name/on/long/path/file.txt /short/file.txt
Changes made to /short/file.txt
will be applied on the original file.
Hard links may be used to move around big files:
$ ls -lh /myapp/dev/
total 10G
-rw-r--r-- 2 root root 10G May 22 12:09 application.bin
ln /myapp/dev/application.bin /myapp/prd/application.bin
Instant copy to different folder, and original file (on /myapp/dev
) may be moved or deleted, without touching the file on /myapp/prd
'Nice programing' 카테고리의 다른 글
PHP에서 스레드 안전 또는 비 스레드 안전은 무엇입니까? (0) | 2020.09.29 |
---|---|
SQL Server의 저장 프로 시저에서 텍스트 검색 (0) | 2020.09.29 |
JavaScript에서 (function () {}) () 구조는 무엇입니까? (0) | 2020.09.29 |
python setup.py 제거 (0) | 2020.09.29 |
MySQL에서 중복 값 찾기 (0) | 2020.09.29 |