Fork函数不执行子进程代码

时间:2017-03-16 11:03:28

标签: c fork

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>

int show_dir_content(char *path);

int show_dir_content(char *path)
{
    char readbuffer[80];
    char buffer[150];
    char uzun[9999];
    int totalfound = 0;
    DIR *d = opendir(path);
    if(d == NULL)
        return -3;
    struct dirent *dir;
    int piper[2];
    pid_t typer = 0;

    while((dir = readdir(d)) != NULL)
    {
        pipe(piper);
        typer = fork();

        if(typer == 0)
        {
            close(piper[0]);
            if(dir->d_type != DT_DIR)
            {   // if the type is not directory  blue
                // printf("%s\n",dir->d_name);
                sprintf(buffer, "%s", dir->d_name);
                write(piper[1], buffer, (strlen(buffer) + 1));
            }

            else if(dir->d_type == DT_DIR && strcmp(dir->d_name, ".") != 0 &&
                    strcmp(dir->d_name, "..") != 0) // if it is a directory

            {

                char d_path[255]; // here I am using sprintf which is safer than
                                  // strcat
                sprintf(d_path, "%s/%s", path, dir->d_name);
                show_dir_content(d_path); // recall with the new path
            }
            exit(0);

            close(piper[1]);
        }
        else if(typer > 0)
        {
            close(piper[1]);
            read(piper[0], readbuffer, sizeof(readbuffer));
            // strcat(uzun,readbuffer);
            // close(piper[0]);

            break;
        }
    }

    while(wait(NULL) > 0)
        ;
    closedir(d);
    // printf("%s x_x\n",uzun);
    return totalfound + 1; // finally close the directory
}

int main(int argc, char **argv)
{

    show_dir_content(argv[1]);

    return (0);
}

它不会在分叉的子代上执行,只在父级上执行,只执行一次。 我使用Linux Mint 18,gcc附带它。 我不知道是什么导致它,它似乎不是分段错误,因为它正确退出。如果有人能在这里看到我的错误,我会更高兴

我在CLion上进行调试。

0 个答案:

没有答案