2013-05-12 78 views
2

我很難創建一個C程序,它會將目錄中的所有大小相加,然後遞歸地進入任何其他目錄來執行相同的操作。C中的多線程目錄工作

不幸的是,它在當前目錄上方的目錄上,並一直重複獲取該目錄的文件,直到發生seg故障。有任何想法嗎?

這是到目前爲止我的代碼:第一個線程函數,然後在主

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

與您的設計的主要問題是工作目錄是進程的屬性,而不是單個線程。因此chdir在一個線程中混淆了所有其他線程。要解決此問題,您需要從每個組件構建相對路徑或絕對路徑名,或使用POSIX 2008(openat等)中添加的新「at」接口。

+0

是的 - 我希望開發人員停止使用'工作目錄'。 – 2013-05-12 09:59:07

+0

工作目錄應該真正被當作程序的只讀輸入,因此只在調用'exec'前才改變。 – 2013-05-12 12:39:29