linux c代码获取当前进程打开了哪些文件

7 篇文章 0 订阅

查看当前进程打开了哪些文件, (同一个线程之间共享进程打开的文件描述符), 如果是在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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值