I need to find the open files of the current process in C Linux. So far all I could figure out was current -> task_struct... then there aren't a log of resources...eventually I'm supposed to get to open_fds
? Also, is the endpoint a bitmap file? How would you get the open files from the bitmap structure or some other weird structure?
on the command line lsof
in C, something like this:
Here is the commented code of a program that prints on screen a list of its own open files:
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
int main() {
// the directory we are going to open
DIR *d;
// max length of strings
int maxpathlength=256;
// the buffer for the full path
char path[maxpathlength];
// /proc/PID/fs contains the list of the open file descriptors among the respective filenames
sprintf(path,"/proc/%i/fd/",getpid() );
printf("List of %s:\n",path);
struct dirent *dir;
d = opendir(path);
if (d) {
//loop for each file inside d
while1 != NULL) {
//let's check if it is a symbolic link
if (dir->d_type == DT_LNK) {
const int maxlength = 256;
# string returned by readlink()
char hardfile[maxlength];
#string length returned by readlink()
int len;
# tempath will contain the current filename among the fullpath
char tempath[maxlength];
sprintf(tempath,"%s%s",path,dir->d_name);
if2!=-1) {
hardfile[len]='\0';
printf("%s -> %s\n", dir->d_name,hardfile);
} else
printf("error when executing readlink() on %s\n",tempath);
}
}
closedir(d);
}
return 0;
}
This code is from: http://mydebian.blogdns.org/?p=229 , which is cached here: http://tinyurl.com/6qlv2nj
See:
How to use lsof(List Opened Files) in a C/C++ application?
http://www.linuxquestions.org/questions/linux-security-4/c-library-for-lsof-183332/
you could also use the lsof
command via a popen
call.