簡體   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