c - Stat errors in pthread (S_ISDIR not working) -
i attempting write program finds size of directory tree size of subdirectories within creating thread each new subdirectory , using thread find size of subdirectory. it's pretty simple program, it's hard debug. having ton of issues s_isdir not working intended (regular files passing if statement , program trying change dir regular files). below code have problem. have each parent directory wait subdirectories finish, don't want each subdirectory wait next one.
#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, = 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 directory passed in if(chdir (p) == -1) { perror("chdir"); exit(1); } // current working directory if(!getcwd (cwd, 2049)) { perror("getcwd") ; return; } // open directory entries within dir = opendir(".") ; if(!dir) { perror("cannot read directory"); return; } while((entry = readdir(dir))) { // call stat on current entry in directory if(stat (entry->d_name, &entry_stat) == -1) { perror("stat error"); } // skip . , .. directories if(strcmp (entry->d_name, ".") == 0) continue; if(strcmp (entry->d_name, "..") == 0) continue; // check if current entry 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 create thread directory %s\n ", paths[numberthreads]) ; exit(1) ; } threads[numberthreads] = temp; // increment number of threads created on level of 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; < numberthreads; i++) { pthread_join(threads[i], null) ; } }
in main, pthread_create function findsize , path user passes in. lots of stat errors, can't figure how fix them..
the current directory not thread-local; it's property of process. you're going end doing nonsense if each thread tries chdir
. either need construct full pathnames based on results readdir
without using chdir
, or use "*at" interfaces (openat
, fstatat
, etc.) open file relative directory file descriptor.
Comments
Post a Comment