So I'm trying to traverse a directory(and subdirectories) and create new processes to sort files and traverse subdirectories. However, I'm having a little trouble understanding how useful my code will be. To my understanding, wait() will sleep the parent process until the child process terminates. Currently my recursive function is
void iterate_dir(char* name){
DIR *dd = opendir(name);
struct dirent *curr;
while((curr = readdir(dd))!=NULL){
if((strcmp(curr->d_name,".")==0 || strcmp(curr->d_name,"..")==0) && curr->d_type==DT_DIR){
continue;
}
int status = -1;
int pid = fork();
if(pid==0){
//child process
if(curr->d_type==DT_DIR){
printf("DIRECTORY:\t%s\n", curr->d_name);
char new_path[strlen(curr->d_name)+strlen(name)+2];
sprintf(new_path,"%s/%s",name,curr->d_name);
//recurse, iterate sub directory
iterate_dir(new_path);
_exit(getpid());
}else{
printf("FILE:\t%s\n", curr->d_name);
//sort the file
_exit(getpid());
}
}
wait(&status);
}
closedir(dd);
}
given and initial directory, it works, but im concerned with the wait() function. I would like the code to continue traversing the directory while the child processes are executing, and currently wait prevents this from happening. But I still need to prevent zombie children. Would using waitpid() instead allow me to have this functionality(ie. allow the loop to continue through the rest of the directory while the child process executes), can I just use 1 wait in main which will prevent all processes created from becoming zombies, or is there a different approach I should take? This is for a school project and I'm required to use fork (not exec) to create a new process for traversing sub directories and a new process for sorting each file.