I am making a sample form of
-ls
function in linux. The program searches all files in a directory. And If there is a directory in the current directory that we are searching for files, Program gets in that directory and prints all files too and so on.. I mean The program prints everything in a directory and directories under current directory. For example If I searches it in Desktop, It gives me all files under Desktop.
I DID this all but The problem is about
fork()
process. I want child process to create
fork()
when It finds a directory and I want parent process to print the name of files.Thats all what I want.But when I run the program, I accrooss a file name several times. I want to see a file or directory name only ones not several times. How can I handle this?
int searchDirectory(char *currDir)
{
struct dirent *direntp;
DIR *dirp;
char currentDir[250];
if ((dirp = opendir(currDir)) == NULL)
{
perror("Failed to open directory");
return 1;
}
while ((direntp = readdir(dirp)) != NULL)
{
if(strcmp(direntp->d_name,".") !=0
&& strcmp(direntp->d_name,"..") != 0 && pid != 0)
printf("PID %d PPID %d : %s\n",getpid(),getppid(), direntp->d_name);
if(direntp->d_type == DT_DIR )
{
if(strcmp(direntp->d_name,".") !=0
&& strcmp(direntp->d_name,"..") != 0 && pid == 0)
{
pid = fork();
numOfDirectories++;
sprintf(currentDir, "%s/%s", currDir, direntp->d_name);
searchDirectory(currentDir);
}
}
}
while ((closedir(dirp) == -1) && (errno == EINTR)) ;
return 0;
}