查看当前进程打开了哪些文件, (同一个线程之间共享进程打开的文件描述符), 如果是在linux终端,可以 lsof -p pid 即可查看对应进程打开的文件,或者查看 proc/pid/fd, 现在想要在代码中获取当前程序打开了哪些文件, 也可以通过 读取 proc/pid/fd进行查看,如下:如果权限允许的话也准备将改demo写成jni给到app中使用,可以方便查看app具体打开占用了哪些文件。
demo结果:
同 ls -lh /proc/pid/fd 效果一样,左边是对应的文件描述符 fd值,右边是指向的文件路径
贴上代码记录下:
用到: opendir() readdir() readlink() sscanf() 相关函数,这几个都可以 man查看帮助文档。
//canok. 20200918
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<dirent.h>
struct fdinfo{
char path[128];
int fd;
struct fdinfo* next;
};
struct fdinfo *getFdlist(){
char fdpath[64]={0};
snprintf(fdpath,sizeof(fdpath),"/proc/%d/fd",getpid());
printf("fdpath:%s\n",fdpath);
DIR *dir;
struct fdinfo * phead=NULL;
struct fdinfo * pcur =NULL;
struct dirent *ptr;
if((dir = opendir(fdpath)) == NULL){
printf("open dir erro:%s\n",fdpath);
return NULL;
}
char destpath[128]={0};
char srcpath[512]={0};
int count =0;
while((ptr=readdir(dir)) != NULL){
//printf("count:%d:%s,%d\n",count++,ptr->d_name,ptr->d_type);
if(strncmp(ptr->d_name,".",1) == 0 || strncmp(ptr->d_name,"..",2)==0){
continue;
}else if(ptr->d_type == 10){ //link file
snprintf(srcpath,sizeof(srcpath),"%s/%s",fdpath,ptr->d_name);
int ret = readlink(srcpath,destpath,sizeof(destpath));
destpath[ret]='\0';
if(ret != -1){
struct fdinfo *new = (struct fdinfo *)malloc(sizeof(struct fdinfo));
new->next = NULL;
strncpy(new->path,destpath,ret<sizeof(new->path)?ret:sizeof(new->path));
sscanf(ptr->d_name,"%d",&(new->fd));
if(phead == NULL){
phead = new;
pcur = new;
}else{
pcur->next = new;
pcur = new;
}
}else{
printf("readlink erro:%s",srcpath);
}
}else{
printf("name:%s type:%d \n",ptr->d_name,ptr->d_type);
}
}
closedir(dir);
return phead;
}
int main(int argc , const char* argv){
FILE* fp = fopen("./test0","w+");
if(fp == NULL){
printf("fopen err [%d%s]\n",__LINE__,__FUNCTION__);
return -1;
}
printf("pid:%d\n",getpid());
//usleep(1*1000*1000);
struct fdinfo * p = getFdlist();
while(p != NULL){
printf("%d --> %s\n",p->fd,p->path);
struct fdinfo *pre = p;
p=p->next;
free(pre);
}
while(1){
usleep(1000*1000);
}
fclose(fp);
return 0;
}