繁体   English   中英

将子进程标准输出重定向到C中的管道

[英]Redirection of child process Standard Output to pipe in C

我尝试理解将子进程“标准输出”重定向到管道的主题,即父进程可以读取它并面对非常奇怪的行为。 在示例父进程fork 3的子进程中,它们执行简单的文件搜索并希望获得输出。 我只收到第一个结果。 这个例子可能有什么问题?

代码如下:

char * searches[] = {
            ".bashrc",
            "NM34_x64.exe",
            "blacklist.sh"
    };
    int fd[2];
    if (pipe(fd) == -1) {
        error("Can't create the pipe");
    }
    __pid_t pids[sizeof(searches)/sizeof(char*)];

    for(int i = 0; i < sizeof(searches)/sizeof(char*); i++){
        __pid_t pid = fork();

        switch (pid) {
            case -1 :
                // ERROR CASE
                error("Failed to make a child process");
                break;
            case 0 :
                // CHILD CASE
                // 1. Redirect Standard Output to pipe
                dup2(fd[1], 1);
                close(fd[0]);
                // 2. Execute command
                if (execl("/usr/bin/find", "/usr/bin/find", "/home", "-name", searches[i], NULL) == -1)
                    error("Failed to execute the command in the child process");
                break;
            default:
                // PARENT CASE
                printf("Created child process with pid %d\n", pid);
                pids[i] = pid;
                // 1. Wait for PID to finish
                int status;
                waitpid(pids[0], &status, 0);
                if (status == -1)
                    error("Failed to wait the child PID");
                printf("Process %d finish his work\n", pids[i]);
                // 2. Redirect pipe to Standard Input
                dup2(fd[0],0);
                close(fd[1]);
                // 3. Read Standard Input
                char line[255];
                while (fgets(line,255,stdin)) {
                    printf("%s", line);
                }
                break;
        }
    }
    return 0;

这是输出:

Created child process with pid 5063
Process 5063 finish his work
/home/user/.bashrc
Created child process with pid 5064
Process 5064 finish his work
Created child process with pid 5065
Process 5065 finish his work

当使用管道进行进程间通信时,直接从管道读取输入到主进程,而不是将其再次重定向到标准输入并在主进程中读取。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM