Created
July 14, 2021 11:21
-
-
Save dwrobel/3c9bd9e70c79d0f093d77bccdc395f19 to your computer and use it in GitHub Desktop.
loop-test.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* loop-test | |
* | |
* Copyright (c) 2021 Damian Wrobel <dwrobel@ertelnet.rybnik.pl> | |
* | |
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED | |
* OR IMPLIED. ANY USE IS AT YOUR OWN RISK. | |
* | |
* Permission is hereby granted to use or copy this program | |
* for any purpose, provided the above notices are retained on all copies. | |
* Permission to modify the code and to distribute modified code is granted, | |
* provided the above notices are retained, and a notice that the code was | |
* modified is included with the above copyright notice. | |
* | |
*/ | |
#include <sstream> | |
#include <string.h> | |
#include <stdio.h> | |
#include <assert.h> | |
#include <fcntl.h> | |
#include <errno.h> | |
#include <sys/ioctl.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <linux/loop.h> | |
#include <unistd.h> | |
int main(int argc, char *argv[]) { | |
const int dev_min = 100; | |
int dev_max = dev_min + 16; | |
const int cfd = open("/dev/loop-control", O_RDWR); | |
assert(cfd >=0); | |
#if 0 | |
// free all unused loop devices | |
while (true) { | |
const int dev = ioctl(cfd, LOOP_CTL_GET_FREE); | |
if (dev >= 0) { | |
std::stringstream lo_path; | |
lo_path << "/dev/loop" << dev; | |
struct stat st; | |
const int rv = stat(lo_path.str().c_str(), &st); | |
if (rv != -1) { | |
const int err = ioctl(cfd, LOOP_CTL_REMOVE, dev); | |
if (err == 0 || err == dev) { | |
printf("loop-test: freeing unused /dev/loop%d\n", dev); | |
} else { | |
printf("loop-test: freeing unused /dev/loop%d failed - %s (rv: %d, errno: %d)\n", dev, strerror(errno), err, errno); | |
break; | |
} | |
} | |
} | |
} | |
#endif | |
for (int dev = dev_min; dev < dev_max; dev++) { | |
usleep(1000); // needed for 3.10 kernel | |
// add a new loop devices | |
const int rv = ioctl(cfd, LOOP_CTL_ADD, dev); | |
if (rv == 0 || rv == dev) { | |
printf("loop-test: added /dev/loop%d\n", dev); | |
} else { | |
printf("loop-test: adding /dev/loop%d failed - %s (rv: %d, errno: %d)\n", dev, strerror(errno), rv, errno); | |
} | |
} | |
for (int dev = dev_min; dev < dev_max; dev++) { | |
usleep(1000); // needed for 3.10 kernel | |
// remove a loop devices | |
const int rv = ioctl(cfd, LOOP_CTL_REMOVE, dev); | |
if (rv == 0 || rv == dev) { | |
printf("loop-test: removed /dev/loop%d\n", dev); | |
} else { | |
printf("loop-test: removing /dev/loop%d failed - %s (rv: %d, errno: %d)\n", dev, strerror(errno), rv, errno); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment