apue实验之:unlink

#if HAVE_CONFIG_H
# include <config.h>
#endif

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include <ace/OS.h>
#include <ace/Log_Msg.h>

#include <iostream>

/* 用unlink删除一个文件的时候,他会自己从目录下消失,但是
 * 磁盘空间不会被立即释放。只有所有打开它的fd都关闭后,
 * 才会被释放
 */
int main(int argc,char* argv[]){
  const char* filename=argv[1];
  if(ACE_OS::open(filename,O_RDWR) <0)
    ACE_ERROR_RETURN((LM_ERROR,ACE_TEXT("%p\n"),
                      ACE_TEXT("打开文件失败")),-1);
  if(ACE_OS::unlink(filename)!=0)
    ACE_ERROR_RETURN((LM_ERROR,ACE_TEXT("%p\n"),
                      ACE_TEXT("删除文件失败")),-1);
  std::cout<<"文件已删除"<<std::endl;
  ACE_OS::sleep(15);
  std::cout<<"done"<<std::endl;
  return 0;
}

这个是测试结果
$ ls > tmp
$ df .
Filesystem 1K-blocks Used Avail Capacity Mounted on
/dev/ad0s3f 69491632 21201954 42730348 33% /usr
$ ./unlink tmp &
[2] 1630
$ 文件已删除
df .
Filesystem 1K-blocks Used Avail Capacity Mounted on
/dev/ad0s3f 69491632 21201954 42730348 33% /usr
$ done
df .
Filesystem 1K-blocks Used Avail Capacity Mounted on
/dev/ad0s3f 69491632 21201952 42730350 33% /usr
我中间也用du测试过。在调用完unlink后,du 显示的结果会立即更改
man页对此的叙述如下

DESCRIPTION
The unlink() system call removes the link named by path from its directory and decrements the link count of the file which was referenced by the link. If that decrement reduces the link count of the file to zero, and no process has the file open, then all resources associated with the file are reclaimed. If one or more process have the file open when the last link is removed, the link is removed, but the removal of the file is delayed until all references to it have been closed. The path argument may not be a directory.

还有很重要的一点是,历史上super user可以用带特殊参数的unlink来删除目录,现在不可以了。

"The unlink() system call traditionally allows the super-user to unlink directories which can damage the file system integrity. This implementation no longer permits it."

此博客中的热门博文

少写代码,多读别人写的代码

在windows下使用llvm+clang

tensorflow distributed runtime初窥