c - C中的目录问题

标签 c exec fork readdir opendir

我正在用 C 为 Linux 编写一个程序,它接收一个目录作为参数,然后为该目录中的每个文件及其每个子目录调用一个名为 monfile 的程序。这是代码:

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <fcntl.h>

#define DIR_ARG 1
#define DUR_ARG 2
#define SEC_ARG 3
#define LOG_ARG 4
#define OP1_ARG 5
#define OP2_ARG 6

int main(int argc, char** argv)
{
    // Teste aos argumentos
    if (argc < 5) {
        printf("Erro! Argumentos insuficientes!\n");
        return -1;
    }

    // Declaração de variáveis
    DIR *dir;
    struct dirent *dentry;
    struct stat stat_entry;

    int fork_result;


    // Testa se o directório passado como argumento é válido
    if ((dir = opendir( argv[DIR_ARG])) == NULL)
    {
        perror(argv[DIR_ARG]);
        exit(2);
    }

    chdir(argv[DIR_ARG]);
    // Ciclo de propagação
    while ((dentry = readdir(dir)) != NULL) {

        stat(dentry->d_name, &stat_entry);
        // Se for ficheiro regular
        if (S_ISREG(stat_entry.st_mode)) {
            fork_result = fork();
            if (fork_result == -1) {
                printf("file fork error!\n");
                exit(1);
            }
            if (fork_result == 0) {
                execlp("monfile", "monfile", argv[SEC_ARG], dentry->d_name, filedes, (char *)NULL);
                printf("Erro no exec!\n");
                exit(1);
            }
        }
        // Se for directório vai criar um novo processo e passar dir para esse directório 
        if (S_ISDIR (stat_entry.st_mode)) {
            fork_result = fork();
            if (fork_result == -1) {
                printf ("dir fork error!\n");
                exit(1);
            }
            if (fork_result == 0) {
                chdir(dentry->d_name);
                dir = opendir (dentry->d_name);
            }
        }
    }



    return 0;
}

现在,这样做的结果是……一大堆 exec 错误消息,然后是一堆 fork 错误消息,即使我只是为包含一个文件和一个子目录的目录调用它。这给我带来了两个问题: a) cicle 是如何进行这么多次迭代的? b) exec 出了什么问题,看看 monfile 是如何构建的,并且与 mondir 在同一个文件夹中?

所以,我决定通过添加来弄清楚程序正在查看的目录

printf("%s\n", dentry->d_name);

在 cicle 的开始,它以某种方式扫描每个目录,即使它是这样调用的:mondir Subfolder1 ...(其他参数),与 mondir 在同一目录中的 Subfolder1。目录问题和 exec 问题,我在这里做错了什么?

最佳答案

readdir 将返回“.”和“..”所以你的代码将遍历目录树,并永远重复每个目录 - fork/exec 轰炸你的机器。

此外,如前所述,find -exec 似乎是一个合理的选择?

关于c - C中的目录问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5525939/

相关文章:

python - 无需执行即可从文件中读取列表和字典

c - 如何在C中仅执行cat

c - 在linux中使用execv使用 './'命令

c - localtime() 函数显示两个相等的日期

c - Glade 布局在编译/GTK_IS_APPLICATION 断言失败时不反射(reflect)

linux - 尝试在bash中使用变量将stderr重定向到/dev/null

c - 如何创建具有不同名称的子进程

c - 如何使用 C 中的信号将多个值从子进程传递到父进程?

c - 内存覆盖问题

c++ - MPI:如何限制对文件系统的访问?