unlink(file_name)

官方描述:

unlink的文档是这样描述的:

    unlink()  deletes  a  name  from  the  filesystem.  If that name was the last link to a file and no processes have the file open the file is deleted and the space it was using is made available for reuse.    If the name was the last link to a file but any processes still have the file open the file will remain in existence  until  the  last  file descriptor referring to it is closed.    If the name referred to a symbolic link the link is removed.    If the name referred to a socket, fifo or device the name for it is removed but processes which have the object open may continue to use it.    首先你要明确一个概念,一个文件是否存在取决于它的inode是否存在,你在目录里看到的是目录项里一条指向该inode的链接,而不是文件的本身.
    当你调用unlink的时候他直接把目录项里的该条链接删除了,但是inode并没有动,该文件还是存在的,这时候你会发现,目录里找不到该文件,但是已经打开这个文件的进程可以正常读写.只有当打开这个inode的所有文件描述符被关闭,指向该inode的链接数为0的情况下,这个文件的inode才会被真正的删除.
    从unlink的名字上就应该能判断出来,unlink含义为取消链接,remove才是删除的意思

 

unlink()函数功能即为删除文件。执行unlink()函数会删除所给参数指定的文件。

unlink()函数返回值: 成功返回0,失败返回 -1

remove()与unlink()的区别:

  • 当remove() 中的pathname指定问文件时,相当于调用unlink 删除文件链接
  • 当remove() 中的pahtname指定为目录时,相当于调用rmdir 删除目录
#include
#include
#include
#include
 
int main()
{
    int fd = open("/zgaoq/q.txt", O_RDWR | O_TRUNC | O_CREAT, 0664);
    if (df < 0) {
        return -1;    
    }
 
    if(unlink("/zgaoq/q.txt") < 0)
    {
        printf("unlink errpr!\n");
    }
    
    char buff[256] = {0};
    write(fd, "hello world!", 12);
 
    if(lseek(fd,0,SEEK_SET) == -1)
    {
        printf("lseek error!\n");
    }
    
    read(fd, buff, 12);
    printf("%s\n",buff);
 
    return 0;
}

因此:执行unlink(filename)之后,并不会立即删除文件,还可以对文件进行读写操作,只有当打开这个文件对应的inode的文件描述符都关闭了之后才会将该文件删除。

 

总结:

调用unlink()的时候,文件还是存在的,只是目录里找不到该文件了,但是已经打开这个文件的进程可以正常读写,只有打开这个文件对应的inode的所有fd都关闭时,这个文件才会被删除。

你可能感兴趣的:(Linux底层,C)