1

現在、新しいサブディレクトリごとにスレッドを作成し、そのスレッドを使用してサブディレクトリのサイズを見つけることにより、ディレクトリツリーのサイズとその中のすべてのサブディレクトリのサイズを見つけるプログラムを作成しようとしています。これは非常に単純なプログラムですが、デバッグするのは非常に困難です。S_ISDIR が意図したとおりに機能しないという問題が山ほどあります (通常のファイルが if ステートメントを渡し、プログラムが dir を通常のファイルに変更しようとしています)。以下は、私が問題のために持っているコードです。サブディレクトリが終了するまで各親ディレクトリを待機させたいのですが、各サブディレクトリを次のディレクトリまで待機させたくありません。

#define NAMESIZE 256
#define NUM_THREADS 100
#define MAX_PATH_LENGTH 500

int totalSum = 0;
pthread_mutex_t sum_mutex ;
pthread_mutex_t thread_mutex ;

void *findSize(void *p)
{
    int levelSum = 0, numberThreads = 0, i = 0;
    DIR *dir ;
    struct dirent *entry ;
    struct stat entry_stat ;
    char cwd[2049] ;
    char threads[NUM_THREADS] ;
    char paths[NUM_THREADS][MAX_PATH_LENGTH];

    char *path = (char*)p ;

    // change into the directory that was passed in
    if(chdir (p) == -1)
    {
        perror("chdir");
        exit(1);
    }

    // get current working directory
    if(!getcwd (cwd, 2049))
    {
        perror("getcwd") ;
        return;
    }

    // open the directory to get entries within it
    dir = opendir(".") ;
    if(!dir)
    {
        perror("Cannot read directory");
        return;
    }

    while((entry = readdir(dir)))
    {
        // call stat on the current entry in the directory
        if(stat (entry->d_name, &entry_stat) == -1)
        {
            perror("stat error");
        }

        // skip the . and .. directories
        if(strcmp (entry->d_name, ".") == 0)
            continue;
        if(strcmp (entry->d_name, "..") == 0)
            continue;

        // check if current entry is a directory
        if(S_ISDIR (entry_stat.st_mode))
        {
            pthread_mutex_lock(&thread_mutex) ;
            strcpy(paths[numberThreads], cwd) ;
            strcat(paths[numberThreads], "/") ;
            strcat(paths[numberThreads], entry->d_name) ;

            pthread_t temp ;

            // create new thread in threads array
            if (pthread_create(&temp, NULL, findSize, (void *)paths[numberThreads]))
            {
                fprintf("failed to create thread for directory %s\n ", paths[numberThreads]) ;
                exit(1) ;
            }

            threads[numberThreads] = temp;

            // increment the number of threads created on this level of the directory tree

            numberThreads++ ;
            pthread_mutex_unlock(&thread_mutex) ;

        }


        if(S_ISREG(entry_stat.st_mode))
        {
            pthread_mutex_lock(&sum_mutex) ;
            int fileSize = entry_stat.st_size ;
            levelSum += fileSize ;
            totalSum += fileSize ;
            pthread_mutex_unlock(&sum_mutex) ;
        }
    }

    void *status ;

    for(i = 0; i < numberThreads; i++)
    {
        pthread_join(threads[i], NULL) ;
    }

}

主に、関数 findSize とユーザーが渡すパスを使用して pthread_create を実行するだけです。多くの統計エラーが発生しますが、それらを修正する方法がわかりません..

4

1 に答える 1