Skip to content

Instantly share code, notes, and snippets.

@chubinou
Created November 28, 2019 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chubinou/dce624b8dfe19f5e6d69deecec3c0052 to your computer and use it in GitHub Desktop.
Save chubinou/dce624b8dfe19f5e6d69deecec3c0052 to your computer and use it in GitHub Desktop.
bool DeviceLister::isRemovable( const std::string& deviceName ) const
{
struct stat info;
int ret = stat(deviceName.c_str(), &info);
if (ret != 0) {
return false;
}
std::stringstream devPath;
devPath << "/sys/dev/block/" << major(info.st_rdev) << ":" << minor(info.st_rdev);
//this should link to /sys/devices/platform/..
char linkPath[PATH_MAX + 1];
if (realpath( devPath.str().c_str(), linkPath ) == NULL)
return false;
while (true)
{
bool hasRemovable = false;
bool hasPartition = false;
std::unique_ptr<DIR, int(*)(DIR*)> dir( opendir( linkPath ), &closedir );
if ( dir == nullptr ) {
LOG_WARN( "can't opendir", linkPath );
return false;
}
dirent* result;
while ( ( result = readdir( dir.get() ) ) != nullptr )
{
if ( strcmp( result->d_name, "removable" ) == 0 )
hasRemovable = true;
else if ( strcmp( result->d_name, "partition" ) == 0 )
hasPartition = true;
else
continue;
}
if (hasRemovable)
{
std::stringstream removableFilePath;
removableFilePath << linkPath << "/removable";
std::unique_ptr<FILE, int(*)(FILE*)> removableFile( fopen( removableFilePath.str().c_str(), "r" ), &fclose );
// Assume the file isn't removable by default
if ( removableFile != nullptr )
{
char buff;
if ( fread(&buff, sizeof(buff), 1, removableFile.get() ) == 1 ) {
return buff == '1';
}
return false;
}
}
if (hasPartition)
{
char* lastSlash = strrchr(linkPath, '/');
if (lastSlash == NULL)
break;
*lastSlash = '\0';
continue;
}
break;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment