一.ln 命令软硬链接介绍
在之前的文章我介绍过软硬链接,这里再次回顾一下。
链接它是有两种,一种被称为硬链接(Hard Link),另外一种被称为符号链接(Symbol link),也叫软链接。建立硬链接时,链接文件和被链接文件必须位于同一个文件系统中,并且不能建立指向目录的硬链接。而对于符号链接,则不存在这个问题。默认情况下,ln 产生硬链接。
首先我们对 hello 文件创建硬链接
[root@ SystemApi]# ls -l hello
-rw-r--r-- 1 root root 1024 Feb 25 09:56 hello
[root@ SystemApi]# ln hello hard_hello
[root@ SystemApi]# ls -l hard_hello
-rw-r--r-- 2 root root 1024 Feb 25 09:56 hard_hello
对于 hello 文件创建软连接(相当于 Windows 系统中的快捷方式)
[root@ SystemApi]# ln -s hello soft_hello
[root@ SystemApi]# ls -l soft_hello
lrwxrwxrwx 1 root root 5 Feb 25 10:57 soft_hello -> hello
二.相关函数
1.link()与 unlink()函数
① 依赖的头文件
#include <unistd.h>
② 函数声明
int link(const char *oldpath, const char *newpath);
int unlink(const char *pathname);
③ 函数的作用
link()函数为一个已经存在的文件创建一个新的链接(也就是硬链接)
unlink()函数是删除软硬链接。
④ 返回值
一旦成功,返回 0,一旦错误,返回-1。并且 erron 被设置了结果
2.symlink()函数
① 依赖头文件
#include <unistd.h>
② 函数声明
int symlink(const char *oldpath, const char *newpath);
③ 函数的作用:创建软链接
④ 返回值
一旦成功,返回 0,一旦错误,返回-1。并且 erron 被设置了结果
3.readlink()函数
① 依赖头文件
#include <unistd.h>
② 函数定义
ssize_t readlink(const char *path, char *buf, size_t bufsiz);
③ 函数作用
读符号链接所指向的文件名字,不读文件内容
④ 返回值
成功返回 buf 填充的大小,失败返回-1