Click here to Skip to main content
14,937,212 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
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)
{   
    /*Only Parent can print the results*/
    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 )
    {
        /*Only child can make process*/
        if(strcmp(direntp->d_name,".") !=0  
            && strcmp(direntp->d_name,"..") != 0 && pid == 0)
        {
            pid = fork();               
            numOfDirectories++;
            //Copies the path and searches in again
            sprintf(currentDir, "%s/%s", currDir, direntp->d_name);
            searchDirectory(currentDir);  //Recursive Step
        }  
    }
}
   while ((closedir(dirp) == -1) && (errno == EINTR)) ;

   return 0; //Sabri Mev at GYTE
}
Posted
Comments
Richard MacCutchan 3-Apr-13 11:48am
   
Don't use fork, just use a recursive function.
Radha.Krishna12 13-May-13 7:46am
   
How can you compare pid == 0 before fork() ??

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900