Chinaunix首页 | 论坛 | 博客
  • 博客访问: 349340
  • 博文数量: 161
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 345
  • 用 户 组: 普通用户
  • 注册时间: 2013-12-13 11:04
文章分类

全部博文(161)

文章存档

2015年(15)

2014年(144)

2013年(2)

我的朋友

分类: LINUX

2014-10-30 14:55:04

看了unlink()函数是对文件的删除,于是写了一个函数进行测试之,结果发现在调用了unlink以后仍然可以对文件进行读写操作,又看了一下书才明白是我没有明白unlink函数的真正含义:删除目录相并减少一个连接数,如果链接数为0并且没有任何进程打开该文件,该文件内容才能被真正删除,但是若又进程打开了该文件,则文件暂时不删除直到所有打开该文件的进程都结束时文件才能被删除。
测试代码:

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<sys/types.h>
  3. #include<sys/stat.h>
  4. #include<fcntl.h>
  5. #include<unistd.h>
  6. int main()
  7. {
  8.     int fd;
  9.     char buf[32];
  10.     struct stat buff;

  11.     if((fd=open("temp.txt",O_RDWR|O_CREAT|O_TRUNC,S_IRWXU))<0){
  12.         printf("create file error!\n");
  13.     }
  14.     stat("temp.txt",&buff);
  15.     printf("temp.link=%d\n",buff.st_nlink);
  16.     link("temp.txt","test.txt");
  17.     stat("test.txt",&buff);
  18.     printf("after link the tem.link =%d\n",buff.st_nlink);
  19.     if(unlink("temp.txt")<0){
  20.         printf("unlink error !\n");
  21.     }
  22.     stat("temp.txt",&buff);
  23.     printf("after unlink tem.link=%d\n",buff.st_nlink);
  24.     if(write(fd,"temp",5)<0){
  25.         printf("write wrror!\n");
  26.     }
  27.     if((lseek(fd,0,SEEK_SET))==-1){
  28.         printf("lseek error!\n");
  29.     }
  30.     if((read(fd,buf,5))<0){
  31.         printf("read error!\n");
  32.     }
  33.     printf("%s\n",buf);
  34.     return 0;
  35. }

有关unlink的更多信息:
http://www.cnblogs.com/codingmonkey/articles/2431078.html


阅读(1366) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~