Click here to Skip to main content
13,092,725 members (63,862 online)
Rate this:
Please Sign up or sign in to vote.
I am making a sample form of
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
process. I want child process to create
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();               
            //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 3-Apr-13 4:49am
Sabri M746
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web02 | 2.8.170813.1 | Last Updated 3 Apr 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100