C pipe, fork, dup, and exec()

末鹿安然 提交于 2019-12-06 08:22:14

问题


I'm trying to pass list of strings through pipe to child process where it should display through /bin/cat using execl(). I had it working earlier except that the pipe did not close so the program kept waiting. Don't know what I did and now it is not working at all. Can someone see my code and tell me what am I doing wrong that the str data is not being displayed by cat in child process?

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

    char *str[] = {"The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"};
    int fds[TOTAL_CHILDREN];
    int writeFds;
    int catPID;
    int status;

    FILE * write_to_child;

    //create pipe
    if (pipe(fds) == -1) {
        perror("creating pipe: failed");
        exit(EXIT_FAILURE);
    }
    pipe(fds);
    //create subprocess for cat child

    switch (catPID) {
        case 0: // successful creation of child
            close(fds[1]); //close write side from parents
            close(0); //close stdin
            dup(fds[0]); //connect pipe from execl cat to stdin

            execl("/bin/cat", "cat", (char *) 0);
            perror("exec failed!");
            exit(20);
            break;

        case -1: //failure
            perror("fork failed: cat process");
            exit(EXIT_FAILURE);

        default: //parent process
            close(fds[0]);

            writeFds = fds[1];
            write_to_child = fdopen(fds[1], "w");

            if (write_to_child == NULL) {
                perror("write to pipe failed");
                exit(EXIT_FAILURE);
            }
            break;


    }

    int i;
    for (i = 0; i < 9; i++){
        fprintf(write_to_child, "%s\n", str[i]);
    }

    fclose(write_to_child);
    close(writeFds);

    wait(&status);

    return (EXIT_SUCCESS);
}

回答1:


You probably want to add the line

catPID = fork();

and I'm not sure why you've got pipe(fds) twice



来源:https://stackoverflow.com/questions/16510069/c-pipe-fork-dup-and-exec

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!