日期:2014-05-16  浏览次数:20533 次

linux下的unlink的问题
最近研究了一下unlink,感觉有点迷糊啊,网上相关资料感觉不多啊,请大家帮帮忙,下面贴出代码(网上找的)
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
int fd;
char buf[32];
struct stat buff;
 if((fd=open("temp.txt",O_RDWR|O_CREAT|O_TRUNC,S_IRWXU))<0){
     printf("create file error!\n");
 }
 stat("temp.txt",&buff);
 printf("temp.link=%d\n",buff.st_nlink);
 link("temp.txt","test.txt");
 stat("test.txt",&buff);
 printf("after link the tem.link =%d\n",buff.st_nlink);
 if(unlink("temp.txt")<0){
     printf("unlink error !\n");
 }
 stat("temp.txt",&buff);
 printf("after unlink tem.link=%d\n",buff.st_nlink);
 if(write(fd,"temp",5)<0){
     printf("write wrror!\n");
 }
 if((lseek(fd,0,SEEK_SET))==-1){
     printf("lseek error!\n");
 }
 if((read(fd,buf,5))<0){
     printf("read error!\n");
 }
 printf("%s\n",buf);
 return 0;
}

代码的运行结果感觉很奇怪:
temp.link=1
after link the tem.link=2
after unlink tem.link=2
temp
问题:
创建文件之后,链接数为1,然后link一下,在printf一下,链接数为2,这个到没啥问题,但unlink("temp.txt")之后,理论上链接数变为1,但是打印出的确是2,为什么呢?
大神们帮帮忙,小弟不胜感激
linux c

------解决方案--------------------
temp.txt 被删除了,第二次stat返回的是-1,打印的值无意义