gpt4 book ai didi

linux - 删除 Linux 程序集 x86 中的文件夹中的所有文件,包括自身

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:40:56 24 4
gpt4 key购买 nike

我写了这段代码,如果从与要删除的文件相同的目录调用,它不会取消链接文件,它会取消文件与其他目录的链接

.section .data
fpath:
.asciz "/home/user/filename" # path to file to delete

.section .text
.globl _start
_start:
movl $10, %eax # unlink syscall
movl $fpath, %ebx # path to file to delete
int $0x80

movl %eax, %ebx # put syscall ret value in ebx
movl $1, %eax # exit syscall
int $0x80

我想要的是取消链接它正在运行的目录中的所有文件(包括它自己)。

最佳答案

您需要先递归删除目录内容,然后才能删除目录本身。以下是 C 语言,但不使用标准库函数,仅使用系统调用:

#define _LARGEFILE64_SOURCE
#define _FILE_OFFSET_BITS 64
#include <dirent.h>
#include <fcntl.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
struct linux_dirent64 {
ino64_t d_ino;
off64_t d_off;
unsigned short d_reclen;
unsigned char d_type;
char d_name[];
};
static void rmrf(int dfd, const char *name) {
unsigned char buffer[16384];
struct linux_dirent64 *dirent;
int fd, off, size;
fd = syscall(SYS_openat, dfd, name, O_RDONLY | O_DIRECTORY);
if (fd == -1) {
syscall(SYS_exit, 1);
}
do {
size = syscall(SYS_getdents64, fd, buffer, sizeof(buffer));
if (size < 0) {
syscall(SYS_exit, 1);
}
for (off = 0; off < size; off += dirent->d_reclen) {
dirent = (struct linux_dirent64 *)&buffer[off];
if (dirent->d_name[0] == '.' &&
(dirent->d_name[1] == '\0' ||
(dirent->d_name[1] == '.' &&
(dirent->d_name[2] == '\0')))) {
continue;
}
if (dirent->d_type != DT_DIR) {
if (!syscall(SYS_unlinkat, fd, dirent->d_name, 0)) {
continue;
}
if (dirent->d_type != DT_UNKNOWN) {
syscall(SYS_exit, 1);
}
}
rmrf(fd, dirent->d_name);
}
} while (off);
syscall(SYS_close, fd);
if (syscall(SYS_unlinkat, dfd, name, AT_REMOVEDIR)) {
syscall(SYS_exit, -1);
}
}
int main() {
const char fpath[] = "/home/user/filename";
if (syscall(SYS_unlink, fpath)) {
rmrf(0, fpath);
}
syscall(SYS_exit, 0);
}

关于linux - 删除 Linux 程序集 x86 中的文件夹中的所有文件,包括自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42866204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com