Created
March 21, 2019 12:04
-
-
Save devendranaga/1b54507c972ea62f7cb34a86aa2859eb to your computer and use it in GitHub Desktop.
find a set of opened files / files currently in use by a process in linux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Find current files in use for a specific process | |
* | |
* @Author: Devendra Naga ([email protected]) | |
* | |
* License MIT | |
*/ | |
#include <stdio.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <dirent.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
int get_open_files(pid_t pid) | |
{ | |
DIR *d; | |
struct dirent *dirp; | |
char dirpath[100]; | |
snprintf(dirpath, sizeof(dirpath), "/proc/%d/fd", pid); | |
// open /proc/pid/fd | |
d = opendir(dirpath); | |
if (!d) { | |
return -1; | |
} | |
while ((dirp = readdir(d)) != NULL) { | |
if (!strcmp(dirp->d_name, ".") || | |
!strcmp(dirp->d_name, "..")) { | |
continue; | |
} | |
char file[512]; | |
char realpath[512]; | |
ssize_t res; | |
memset(file, 0, sizeof(file)); | |
memset(realpath, 0, sizeof(realpath)); | |
// get the real file name that's in /proc/pid/fd/ | |
snprintf(file, sizeof(file), "%s/%s", dirpath, dirp->d_name); | |
// validate if its not a directory .. we are looking for only files | |
struct stat file_type; | |
int ret; | |
ret = stat(file, &file_type); | |
if ((ret != -1) && (!S_ISDIR(file_type.st_mode))) { | |
res = readlink(file, realpath, sizeof(realpath)); | |
if (res != -1) { // here's the rael name of the file | |
printf("file %s\n", realpath); | |
} | |
} | |
} | |
closedir(d); | |
return 0; | |
} | |
int main() | |
{ | |
FILE *fp; | |
// testing | |
fp = fopen("./lsof.txt", "w"); | |
get_open_files(getpid()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment