通过先unlink()后close()创建安全的临时文件

使用POSIX(Portable Operating System Interface)标准文件操作函数可以创建安全的临时文件:
使用open()创建临时文件。
马上调用unlink()删除文件,该临时文件将被从当前目录中去除;但inode会等到所有打开的文件描述符都关闭(reference count = 0)时才被删除。在此之前变成一个孤儿(orphan inode),使用ls 或者 du 都无法查看到该文件;但是对所在的文件系统进行df 还是可以知道该文件的存在。
使用完毕后调用close()关闭文件,这样文件就会在文件系统中完全消失。
这样创建的临时文件具有如下安全性:
如果程序崩溃,操作系统会关闭该程序打开的所有文件。该临时文件会在关闭时消失,而不会依然保留在文件系统中。
用户无法对该文件进行存取,也就无法对里面的内容进行监控、过滤等动作。
当然还有其他方式:加密,多次覆盖重写文件存储区域防止数据恢复,等等。或者可以将多种方式结合以满足较高的安全要求。

编译执行:
$ gcc -o unlink_before_close unlink_before_close.c $ ./unlink_before_close
============================================================================

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <err.h>

int main(int argc, char *argv[])
{
    if (open("tempfile", O_RDWR|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0)
        errx(1, "open error");

    if (unlink("tempfile") < 0)
        errx(1, "unlink error");

    printf("file unlinked\n");
    sleep(15);
    printf("done\n");

    exit(0);
}

猜你喜欢

转载自boisterous.iteye.com/blog/962981