source: tags/1.0/test/remove_links_main.cpp @ 5

Last change on this file since 5 was 5, checked in by willem, 11 years ago

willem

File size: 2.2 KB
Line 
1#include <errno.h>
2#include <dirent.h>
3#include <stdio.h>
4#include <stdlib.h>
5#include <sys/types.h>
6#include <sys/stat.h>
7#include <unistd.h>
8#include <limits.h>
9
10#include <iostream>
11
12int remove_links(const std::string path, const std::string dirl, int timer)
13{
14  // removes hard links in directory "dirl" to file "path"
15  // in directory "dir", if they are older than "time" seconds.
16  // Method:
17  // using readdir, examine all components of dirl and see
18  // if they have the same inode as "path". If so, remove, unless
19  // the realname is the same as the realname of "path"
20  //
21  DIR *pdir;
22  struct dirent *pent;
23  int rc;
24  struct stat buf;
25
26  pdir = opendir(dirl.c_str());
27  if (!pdir)
28  {
29    std::cerr << "Cannot read link directory '"<<dirl<<"'"<<std::endl;
30    return 1;
31  }
32  rc = stat(path.c_str(),&buf);
33  if (rc !=0)
34  {
35    std::cerr << "Cannot stat '"<<path<<"'"<<std::endl;
36    return 1;
37  }
38  ino_t inodenr = buf.st_ino;
39  char rpathc[PATH_MAX+1];
40  realpath(path.c_str(),rpathc);
41  std::string rpath = rpathc;
42  std::cerr<<"TD: basefile '"<<rpath<<"'"<<std::endl;
43  std::string rpath1;
44 
45  while ((pent=readdir(pdir)))
46  {
47    struct stat buf;
48    std::string name = pent->d_name;
49    if (name == ".") continue;
50    if (name == "..") continue;
51    realpath((dirl+"/"+name).c_str(),rpathc);
52    rpath1 = rpathc;
53    std::cerr<<"TD: looking at '"<<rpath1<<"'"<<std::endl;
54    if (rpath != rpath1)
55    {
56      int rc = stat(rpath1.c_str(),&buf);
57      if (rc != 0)
58      {
59        std::cerr<<"Cannot stat '"<<rpath1<<"'"<<" this cannot happen!" << std::endl;
60        return 1;
61      }
62      if (buf.st_ino == inodenr)
63      {
64        std::cerr << "time: " << time(0) << " " << buf.st_mtime << " " << timer << std::endl;
65        if (time(0) > buf.st_mtime + timer)
66        {
67          int rc = unlink(rpath1.c_str());
68          if (rc == 0)
69            std::cerr<<"Unlinked '"<<rpath1<<"'"<<std::endl;
70          else
71            std::cerr<<"Could not unlink '"<<rpath1<<"'"<<std::endl;
72        }
73        else
74          std::cerr << "TD: not unlinking because time: '"<<rpath1<<"'"<<std::endl;
75      }
76    }
77    else
78      std::cerr<<"TD: not unlinking '"<<rpath1<<"'"<<std::endl;
79  }
80  return 0;
81}
82int main()
83{
84  std::string poolfilename="pool";
85  std::string linkdirname="linkdir";
86  int timer = 60;
87  remove_links(poolfilename, linkdirname,timer);
88  return 0;
89}
Note: See TracBrowser for help on using the repository browser.