apue第四章(二)

    技术2022-05-19  19

    我的目标是:让我的家人生活得更好

     

    7unix的文件系统

       unix的文件系统结构:主要包括有i节点,数据块,目录块。是对数据块和目录块的编号。 一个i节点可以指向多个数据块或者目录快。一个文件或者一个目录对应一个i节点(也就是对应一个编号)。一个i节点可以对应一个多个文件。在struct stat st_link与之对应。这个在unix中叫做硬链接数。

    例如 下面testumask0testumask1就是硬链接数为2,删除其中一个并不能释放磁盘数据,当硬链接数为0时才会释放磁盘空间。

    white@white-desktop:/home/junjun/apue/chapter4$ ls -la

    总计 48

    -rw-r--r-- 1 white white  303 2011-03-07 16:27 testCat.c

    -rw-r----- 2 white white   14 2011-03-08 11:10 testumask0

    -rw-r----- 2 white white   14 2011-03-08 11:10 testumask1

        

    由于i节点编号只在本文件系统有效,所以硬链接只能在本文件系统有效,不能跨文件系统

     

      unix中使用int link(char *file1, char * file2) 创建硬链接。

      使用unlink(char * filename)删除一个文件(文件的硬链接减一)

      使用rmdir(char * fileName)删除一个目录

      stdio.h中也有一个void remove(char *filename)实现了unlinkrmdir的功能。

    /*创建硬连接*

    #include<unistd.h>

    #include<errno.h>

    int main(int argc, char * argv[])

    {

        if(argc !=3){printf("usage: prog pathname pathname");exit(-1);}

        if(link(argv[1],argv[2]) < 0) perror("link");

           

    }/

     

    8、临时文件

       unix中一个文件如果其硬连接数为零了还不一定立即释放其使用的数据块。当一个文件的硬连接数减少为0后、如果这个文件已经被某进程打开,不会立即清除这个文件占有的数据区,当进程结束后才会释放。这样那我们可以这样来实现一个临时文件。

    int fid = creat(“tempfile”);

    unlink(“tmpfile”);

    例如:

    #include<unistd.h>

    #include<errno.h>

    #include<fcntl.h>

    #include<sys/types.h>

    #include<sys/stat.h>

    int main()

    {

      int fid = open("tempfile",O_CREAT|O_RDWR,S_IRUSR|S_IRGRP);

    if(fid < 0) {perror("open");exit(1);}

      sleep(5);

      printf("unlink/n");

      unlink("tempfile");

      sleep(5);

    }

     

    执行结果

    white@white-desktop:/home/junjun/apue/chapter4$ ./a.out &

    [1] 2520

    white@white-desktop:/home/junjun/apue/chapter4$ ls  //出现了tmpfile

    4-1.c  4-2.out  linkTest.c  test       testumask0  tmpfileTest.c

    4-2.c  a.out    tempfile    testCat.c  testumask1

    white@white-desktop:/home/junjun/apue/chapter4$ unlink

     

    white@white-desktop:/home/junjun/apue/chapter4$ ls

    //unlink后没有了tmpfile 但是可以对其进程操作

    4-1.c  4-2.out  linkTest.c  testCat.c   testumask1

    4-2.c  a.out    test        testumask0  tmpfileTest.c


    最新回复(0)