c - 在 linux 中列出目录时的无限递归

标签 c linux recursion filesystems

我尝试编写程序,其中一部分列出了所有目录(尤其是从/开始),但我遇到了/proc/self 的问题,它是无限递归的(我得到/proc/self/task/4300/fd/3/proc/self/task/4300/fd/3/proc/self/task/4300/fd/3/proc/...等等)。有什么好的处理方法?

编辑:程序是用 C 语言编写的,我使用 opendir()、readdir()

最佳答案

您可以使用 S_ISLNK macro to test the st_mode field通过调用 lstat 返回。如果文件是符号链接(symbolic link),请不要尝试跟随它。

[user@machine:~]:./list | grep link
/proc/mounts is a symbolic link
/proc/self is a symbolic link

示例代码

#include <stdio.h>     // For perror
#include <stdlib.h>
#include <sys/types.h> // For stat, opendir, readdir
#include <sys/stat.h>  // For stat
#include <unistd.h>    // For stat
#include <dirent.h>    // For opendir, readdir

const char *prefix = "/proc";

int main(void)
{
    DIR *dir;
    struct dirent *entry;
    int result;
    struct stat status;
    char path[PATH_MAX];

    dir = opendir(prefix);
    if (!dir)
    {
        perror("opendir");
        exit(1);
    }

    entry = readdir(dir);
    while (entry)
    {
        result = snprintf(path, sizeof(path), "%s", prefix);
        snprintf(&path[result], sizeof(path) - result, "/%s", entry->d_name);
        printf("%s", path);

        result = lstat(path, &status);
        if (-1 == result)
        {
            printf("\n");
            perror("stat");
            exit(2);
        }

        if (S_ISLNK(status.st_mode))
        {
            printf("%s", " is a symbolic link");
        }

        printf("\n");

        entry = readdir(dir);
    }

    return(0);
}

关于c - 在 linux 中列出目录时的无限递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4740818/

相关文章:

c - 无法读取 C 中的字符

c - Gstreamer C 代码因流停止而失败,原因未协商 (-4)

C:线程安全记录到文件

linux - 如何在 'when'模块中包含特殊字符?

FFmpeg 可以在 VP8 编解码器中编码视频吗?

java - 从 spring boot war 文件中运行 linux 命令

c - 遍历 proc 中的目录

c - 将递归函数中的几个字符串存储到 struct c

c - 可视化 C 中的递归

python - n 个数字的最小公倍数,使用递归