/*
* text.cpp
*
* Created on: Mar 14, 2022
* Author: lu
*/
#include <iostream>
#include <stdio.h>
/*
* lsof | grep filename
* 如果有输出(或者退出状态$?=0) 表示filename正在被操作
* 如果没输出(或者退出状态非0) 表示filename没在被操作
*/
static int get_file_state(std::string &filename) //
{
char buf[10240] = {0};
FILE *pf = NULL;
std::string str_cmd = "lsof | grep " + filename;
if( (pf = popen(str_cmd.c_str(), "r")) == NULL )
{
return -1;
}
std::string str_result;
while(fgets(buf, sizeof buf, pf))
{
str_result += buf;
}
pclose(pf);
unsigned int isize = str_result.size();
if(isize > 0 && str_result[isize - 1] == '\n') // linux
{
str_result = str_result.substr(0, isize - 1);
}
if(str_result.find(filename) == std::string::npos )//不存在。
{
return 0;
}
return -1;
}
int main()
{
int err=0;
std::string haha = "./haha";
err = get_file_state(haha);
if(err)
{
printf("file is busy\n");
}
return 0;
}
|