Q:

Multithreaded directory work in C

I'm having difficulty creating a C program that will add up all the sizes in a directory then recursively go into any other directories to do the same thing. 
Unfortunately, it goes on directory above the current directory and keeps getting the files of that directory over and over again until a seg fault. Any ideas?
This is my code so far: first the thread function then the corresponding part in main
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++;
   }
 } 
} 

Code in 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;
}

A:

The main problem with your design is that the working directory is a property of the process, not a single thread. Thus chdir in one thread messes up all the other threads. To solve the problem you either need to build relative or absolute pathnames from each component, or use the new "at" interfaces added in POSIX 2008 (openat, etc.`).

