readdir在使用readlink时被阻止,但是readdir_r没问题。为什么?

时间:2014-07-23 02:02:19

标签: c linux unix

简单的代码演示在这里:

我在while循环中调用readdir。但它被阻止了!

readdir_r没问题。

但这里没有线索或信号!!!

    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <assert.h>
    #include <string.h>
    #include <dirent.h>

    #define NAME_LEN    256


    /* receive one arguement as a directory name.
     * you should keep at least one symlink in it.
     * e.g, mkdir test; touch test/a; cd test; ln -s a aa
     * then, deal_dir("test")
     */
    void deal_dir(char const *dirname)
    {
        DIR *dir; 
        struct dirent *ent;


        if (chdir(dirname) < 0) {
            perror("chdir");
            exit(EXIT_FAILURE);
        }
        dir = opendir(".");

        // ent = malloc(sizeof(struct dirent) + NAME_LEN);

        while (1) {
            // struct dirent *dir_read_res;
            // assert(readdir_r(dir, ent, &dir_read_res) == 0);
            // if (!dir_read_res)
            //   break;
            ent = readdir(dir);
            if (!ent)
                break;

            char *name = ent->d_name;
            struct stat stat_buf;

            bzero(&stat_buf, sizeof(stat_buf));
            if (lstat(name, &stat_buf) < 0) {
                perror("stat");
                exit(-1);
            }

            if ((!S_ISREG(stat_buf.st_mode) && !S_ISLNK(stat_buf.st_mode)) ||
                    (strcmp(name, ".") == 0 || strcmp(name, "..") == 0))
                continue;

            if (S_ISLNK(stat_buf.st_mode)) {
                char link2[NAME_LEN];
                int sz = readlink(name, link2, NAME_LEN);
                assert(sz >= 0 && sz < NAME_LEN);
                link2[sz] = '\0';
                strncpy(name, link2, NAME_LEN);
            }

            printf("real name is: %s\n", name);
        }

        closedir(dir);
    }


    int main(int argc, char *argv[])
    {
        deal_dir(argv[1]);
    }

但是,使用readdir_r是可以的。

没有线程也没有信号。为什么要读readdir_r?

您可以取消注释readdir_r行并重新测试。

0 个答案:

没有答案