下面代码效果是查出哪个进程打开了指定文件,可以查出打开文件进程的PID以及该进程所在linux的绝对路径(只能查出一个,想得出全部的需要小改一下代码),并且可以自己选择是否kill掉这个进程
#include <stdio.h>
#include <string.h>
#include <stdlib.h>//执行命令行输出并且得到结果
//cmd shell命令
//result 输出结果
void executeCMD(const char* cmd,char *result)
{char buf_ps[1024];char ps[1024]={0};FILE* ptr;strcpy(ps,cmd);if((ptr=popen(ps,"r"))!=NULL){while(fgets(buf_ps,1024,ptr)!=NULL){//shell print in resultprintf("shell print:%s",buf_ps);strcpy(result,buf_ps);result[strcspn(result,"\n")]='\0';if(strlen(result)>1024)break;}pclose(ptr);ptr = NULL;}else{printf("popen %s error\n",ps);}
}//根据pid杀死线程
void killpid(int pid)
{char order[512]={0};char ret[512]={0};if(sprintf(order,"kill -9 %d",pid)<0)printf("sprintf() error!\n");executeCMD(order,ret);//printf("ret : %s",ret);//printf("???");return;
}//得到线程pid
//filePath 文件绝对路径
//pidResult 返回使用这个文件的进程
void getPid(const char* filePath,char* pidResult)
{char order[256]={0};if(sprintf(order,"/usr/bin/lsof %.*s | awk \'{print $2}\' | grep -v \"PID\"",(int)strlen(filePath),filePath)<0)printf("sprintf() error! function in getPid\n");executeCMD(order,pidResult);return;
}int main()
{char result[256]={0};char order[256]={0};char resultPid[32]={0};char filePath[256]={0};//指定的文件路径sprintf(filePath,"/home/projects/protectFile/ld_test.c");getPid(filePath,resultPid);int pid = atoi(resultPid);if(sprintf(order,"readlink -f /proc/%d/exe",pid)<0)printf("sprintf() error! function in main\n");executeCMD(order,result);if(0) //这里条件判断这个进程允不允许打开文件,不允许就kill掉{killpid(pid);} return 0;
}
printf输出
shell print:2189
shell print:/home/projects/protectFile/continueOpenFile.exe