2

ディレクトリ内のすべてのサイズを合計してから、他のディレクトリに再帰的に移動して同じことを行う C プログラムを作成するのに苦労しています。

残念ながら、現在のディレクトリの上のディレクトリに移動し、セグ フォールトが発生するまで、そのディレクトリのファイルを何度も取得し続けます。何か案は?

これはこれまでの私のコードです。最初にスレッド関数、次にメインの対応する部分

void *directorywork(void *path) 
{

 /*some declarations here*/

 size_t numbers_len = sizeof(statbuf.st_size)/sizeof(int);

 dp = opendir(path);
 chdir(path);

 while((dirnext = readdir(dp)) != NULL)
 {  
   stat(dirnext->d_name,&statbuf);

   // passing over directories above the requested directory  

   if(strcmp(dirnext->d_name, ".") == 0)
   { 
     continue;
   }

   if(strcmp(dirname->d_name, "..") == 0) 
   {  
     continue;
   }

   if(!S_ISDIR(statbuf.st_mode))
   {
     printf("File %s is %d bytes\n", dirnext->d_name, (int)statbuf.st_size);
     pthread_mutex_lock(&crit);
     fsum = sum + (int)statbuf.st_size;
     pthread_mutex_unlock(&crit); 
   }
   else
   {
     pthread_create(&tids[i++], NULL, directorywork, (void*)path);
     i++;
   }
 } 
} 

コードmain():

int main(int argc, char *argv[]) {

    /*some string input parsing*/

    int k; 

    psize(NULL); 

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

    printf("Total sum of all directories is: %d\n\n", fsum);

    free(firstpath); 
    free(path);     

    return 0;
}
4

1 に答える 1

5

設計の主な問題は、作業ディレクトリがプロセスのプロパティであり、単一のスレッドではないことです。したがってchdir、1 つのスレッドで他のすべてのスレッドが台無しになります。この問題を解決するには、各コンポーネントから相対パス名または絶対パス名を作成するか、POSIX 2008 で追加された新しい「at」インターフェイス (openatなど) を使用する必要があります。

于 2013-05-12T00:51:48.420 に答える