apue第四章(二)

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

 

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值