前述:
linux下删除一个文件需要满足两个条件:
1.文件的链接计数为0
2.没有进程打开该文件
我们即使使用rm命令删除了文件,实际上如果有进程打开了该文件,该文件的内容实际上没有被删除,进程仍然可通过fd操控这个文件。
删除一个文件时,内核首先检查打开该文件的进程个数;如果这个技术达到0,内核再去检查其链接计数;如果计数也是0.那么就删除该文件的内容。
系统提供了unlink函数,这种特性经常被程序用来确保即使是在程序奔溃时,它所创建的临时文件也不会遗留下来。进程用open创建一个文件,然后立即调用unlink,因为该文件仍旧是打开的,所以不会将其内容删除。只有当进程关闭该文件或终止时,该文件的内容才被删除。
测试例子:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main()
{
//创建文件
int fd = open("./test.temp", O_RDWR | O_CREAT | O_EXCL, 0777);
if (fd == -1) {
perror("create file fail");
return -1;
} else {
printf("create file success\n");
}
//删除文件,这里也可以用remove函数
int res = unlink("./test.temp");
if (res == -1) {
perror("unlink fail");
return -1;
}
//写
char buf1[] = "hello world!";
int n = write(fd, buf1, strlen(buf1));
if (n == -1) {
perror("write file fail");
return -1;
}
//读
lseek(fd, 0, SEEK_SET);
char buf2[32] = {};
n = read(fd, buf2, strlen(buf1));
if (n == -1) {
perror("read file fail");
return -1;
}
printf("read: %s\n", buf2);
//为了暂停观察文件
sleep(60);
return 0;
}
End;