00001
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 #include <config.h>
00022
00023 #include "fdtracker.h"
00024
00025 #include "safeunistd.h"
00026 #include "safedirent.h"
00027 #include "safeerrno.h"
00028
00029 #include <iostream>
00030 #include <cstdlib>
00031 #include <cstring>
00032 #include <set>
00033
00034 #include "str.h"
00035
00036 using namespace std;
00037
00038 FDTracker::~FDTracker()
00039 {
00040 #ifndef __WIN32__
00041 if (dir_void) {
00042 DIR * dir = static_cast<DIR*>(dir_void);
00043 closedir(dir);
00044 }
00045 #endif
00046 }
00047
00048 void
00049 FDTracker::init()
00050 {
00051 #ifndef __WIN32__
00052 DIR * dir = opendir("/proc/self/fd");
00053
00054 if (!dir) return;
00055 dir_void = static_cast<void*>(dir);
00056
00057 while (true) {
00058 errno = 0;
00059 struct dirent * entry = readdir(dir);
00060 if (!entry) {
00061 if (errno == 0)
00062 break;
00063 cout << "readdir failed: " << strerror(errno) << endl;
00064 exit(1);
00065 }
00066
00067 const char * name = entry->d_name;
00068 if (name[0] < '0' || name[0] > '9')
00069 continue;
00070
00071 int fd = atoi(name);
00072 fds.insert(fd);
00073 }
00074 #endif
00075 }
00076
00077 bool
00078 FDTracker::check()
00079 {
00080 bool ok = true;
00081 #ifndef __WIN32__
00082 DIR * dir = static_cast<DIR*>(dir_void);
00083 if (!dir) return true;
00084 rewinddir(dir);
00085
00086 message.resize(0);
00087
00088 while (true) {
00089 errno = 0;
00090 struct dirent * entry = readdir(dir);
00091 if (!entry) {
00092 if (errno == 0)
00093 break;
00094 cout << "readdir failed: " << strerror(errno) << endl;
00095 exit(1);
00096 }
00097
00098 const char * name = entry->d_name;
00099
00100
00101 if (name[0] < '0' || name[0] > '9')
00102 continue;
00103
00104 int fd = atoi(name);
00105 if (fds.find(fd) != fds.end()) continue;
00106
00107 message += ' ';
00108 message += str(fd);
00109
00110 string filename = "/proc/self/fd/";
00111 filename += name;
00112
00113 char buf[1024];
00114 int res = readlink(filename.c_str(), buf, sizeof(buf));
00115 if (res > 0) {
00116 message += " -> ";
00117 message.append(buf, res);
00118 }
00119
00120
00121 fds.insert(fd);
00122 ok = false;
00123 }
00124 #endif
00125 return ok;
00126 }