Linux的学习笔记
- link、unlink
- 1. 共享盘块
- 2. link() 为已经存在的文件创建目录项(硬链接)
- 头文件包含和函数声明
- 3. unlink() 删除一个文件的目录项
- 头文件包含和函数声明
- Linux下删除文件的机制:
- demo
- 4. unlink 使用注意及隐性回收
- demo
- 4.1 编译后运行,发生阻塞,并生成 temp.txt 文件,成功!
- 4.2 加入段错误后,在进行编译,运行
- 4.3 将 unlink 提前到最前面,出现段错误,但是 temp.txt 被干掉了
- 5. 隐式回收(隐式回收系统资源)
- 6. readlink 读符号链接本身内容,得到链接所指向的文件名
- 头文件包含及函数声明
link、unlink
1. 共享盘块
在 Linux 系统中,目录项游离于 inode 之外,文件名与 inode 并存于 dentry 中。
其目的为了实现文件共享。Linux 允许多个目录项共享一个 inode,即共享盘块(data)。不同文件名,但在内核中其实是一个文件。
2. link() 为已经存在的文件创建目录项(硬链接)
头文件包含和函数声明
man 2 link
#include<unistd.h>int link(const char* oldpath, const char* newpath);
返回值:
- 成功:0
- 失败:-1,errno
ln t.c t.hard # 创建硬链接
3. unlink() 删除一个文件的目录项
头文件包含和函数声明
#include<unistd.h>int unlink(const char* pathname);
Linux下删除文件的机制:
-
不断将 st_nlink - 1, 直到减到0为止。无目录项对应的文件,将会被操作系统择机释放。(具体时间由系统内部调度算法决定)
-
文件被删除,只是让文件具备勒被释放的条件
demo
/* 给硬链接改名,创建一个,删除原来的 */
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<errno.h>int main(int argc, char * argv [ ])
{link(argv[1], argv[2]);unlink(argv[1]);return 0;
}
4. unlink 使用注意及隐性回收
由于 Linux 的删除文件机制,若使用 unlink 将文件的硬链接减到0了,没有 dentry 对应,但文件不会马上被释放掉。要等到所有打开该文件的进程关闭该文件,系统才会挑时间将文件释放
demo
`#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>int main(void)
{int fd;char* p = "test of unlink\n";char* p2 = "after write something.\n";fd = open("temp.txt",O_RDWR|O_CREAT|O_TRUNC, 0644);if (fd < 0){perror("open temp error");exit(1);}int ret = write(fd, p, strlen(p));if (ret == -1){perror("----write error");}printf("hi! I'm printf\n");ret = write(fd, p2, strlen(p2));if (ret == -1){printf("----write error");}printf("Enter anykey continue\n");getchar();close(fd);ret = unlink("temp.txt");if (ret < 0){perror("unlink error");exit(1);}
}
4.1 编译后运行,发生阻塞,并生成 temp.txt 文件,成功!
程序运行期间 temp.txt 存在,程序运行结束,文件被干掉
4.2 加入段错误后,在进行编译,运行
发生段错误, temp.txt 没有被干掉
4.3 将 unlink 提前到最前面,出现段错误,但是 temp.txt 被干掉了
发生段错误后,close(fd)并未运行,程序运行结束,系统自动关闭
5. 隐式回收(隐式回收系统资源)
当进程结束运行,所有该进程打开的文件会被关闭,申请的内存空间会被释放。系统这一特性称为隐式回收系统资源
6. readlink 读符号链接本身内容,得到链接所指向的文件名
头文件包含及函数声明
man 2 readlink
#include<fcntl.h>
#include<unistd.h>ssize_t readlink(const char* path, char *buf,size_t bufsize)