Created
August 15, 2025 06:49
-
-
Save BenSYZ/87938137bfd8cf1ce2240fdacb416570 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
* remove loop device created by losetup | |
* | |
* SPDX-License-Identifier: LGPL-2.1-or-later | |
* | |
* Copyright (C) 2025 Ben Song <[email protected]> | |
* | |
* This library is free software; you can redistribute it and/or modify it | |
* under the terms of the GNU Lesser General Public License as published by the | |
* Free Software Foundation; either version 2.1 of the License, or (at your | |
* option) any later version. | |
* | |
* This library is distributed in the hope that it will be useful, but WITHOUT | |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License | |
* for more details. | |
* | |
* You should have received a copy of the GNU Lesser General Public License | |
* along with this library; if not, write to the Free Software Foundation, Inc., | |
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA | |
*/ | |
/* | |
* Please refer to `man 4 loop` | |
* | |
* This scripts will delete node created by losetup, not by mknod | |
* Case 1 | |
* 1. losetup /dev/loop0 a.img | |
* 2. losetup -d /dev/loop0 | |
* 3. ./rm_loop 0 # OK | |
* | |
* Case 2: | |
* 1. losetup /dev/loop0 a.img | |
* 2. losetup -d /dev/loop0 | |
* 3. rm /dev/loop0 | |
* 4. losetup /dev/loop0 a.img # <- failed | |
* 5. sudo mknod /dev/loop0 b 7 0 | |
* 6. losetup /dev/loop0 a.img # <- success | |
* 7. losetup -d /dev/loop0 | |
* | |
* after ./rm_loop 0, you need to delete the manual created /dev/loop0 | |
*/ | |
#include <stdio.h> | |
#include <sys/ioctl.h> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#include <linux/loop.h> | |
#include <errno.h> | |
#include <stdlib.h> | |
int main(int argc, char* argv[]){ | |
int ret=0; | |
if (argc != 2){ | |
ret=-1; | |
printf("Usage:\n"); | |
printf("%s <loop index to delete>\n", argv[0]); | |
goto final; | |
} | |
long loop_dev_index=atol(argv[1]); | |
int fd = open("/dev/loop-control", O_RDWR); | |
if (fd < 0){ | |
perror("Failed to open /dev/loop-control"); | |
ret=errno; | |
goto final; | |
} | |
if ( ioctl(fd, LOOP_CTL_REMOVE, loop_dev_index) < 0 ){ | |
printf("/dev/loop"); | |
fflush(stdout); | |
perror(argv[1]); | |
ret=errno; | |
goto close_fd; | |
} | |
close_fd: | |
close(fd); | |
final: | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment