Click here to Skip to main content
11,711,440 members (84,504 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C Linux system Process
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 at 3-Apr-13 11:48am
Don't use fork, just use a recursive function.
Radha.Krishna12 at 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
0 Sergey Alexandrovich Kryukov 529
1 OriginalGriff 200
2 Peter Leow 164
3 Abhinav S 125
4 CHill60 115
0 Maciej Los 95
1 Richard MacCutchan 90
2 Abhinav S 90
3 OriginalGriff 80
4 Member 4653839 50

Advertise | Privacy | Mobile
Web01 | 2.8.150819.1 | Last Updated 3 Apr 2013
Copyright © CodeProject, 1999-2015
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