|
C++判断文件是否被占用
/*
* lsof | grep filename
* 如果有输出(或者退出状态$?=0) 表示filename正在被操作
* 如果没输出(或者退出状态非0) 表示filename没在被操作
*/
static int get_file_state(CString filename) //
{
char buf[10240] = {0};
FILE *pf = NULL;
CString str_filename = _T("lsof | grep ") + filename;
size_t iLengh = str_filename.GetLength() * 2 + 1;
size_t iConverted = 0;
char * str_cmd = new char[iLengh];
if( (pf = open(str_cmd , _T( "r"))) == NULL )
{
return -1;
}
std::string str_result;
while(fgets(buf, sizeof buf, pf))
{
str_result += buf;
}
close(pf);
pf.close();
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(str_cmd) == std::string::npos )//不存在。
{
return 0;
}
return -1;
} |
|