在活着和运行时从子进程中读取和写入

时间:2017-09-25 02:14:47

标签: c process pipe

我希望在父母和孩子之间传递信息。目前,我正在通过读取文件描述符的另一端,从父级的STDERR到子级的STDIN和读取子级的STDOUT。我已经完成了下面的工作,但是在我能够阅读之前,我正在努力解决需要退出的孩子。如何逐行阅读孩子的输出

子进程之间的循环

for (int currentP = 0; currentP < inputs.playerCount; currentP++) {
            char currentPlayerC[2];
            sprintf(currentPlayerC, "%d", currentP);
            char* currentPlayerT = argv[3+currentP];

            int fds[2];
            int fds1[2];
            pipe(fds);
            pipe(fds1);
            char buff[10];
            memset(buff, 0, sizeof(buff));
            if ((pids[currentP] = fork()) < 0) {
                    perror("fork");
                    abort();
            } else if (pids[currentP] == 0) { //Child
                    close(fds[PIPE_READ]);
                    close(fds1[PIPE_WRITE]);
                    dup2(fds[PIPE_WRITE], STDOUT_FILENO);
                    dup2(fds1[PIPE_READ], STDIN_FILENO);
                    close(fds1[PIPE_READ]);
                    close(fds[PIPE_WRITE]);
                    execlp(CHILD PROCESS THAT PRINTS TO STDOUT READS FROM STDIN))
                    _exit(0);
                    return BADSTART;
            } else  { //parent
                    dup2(fds1[PIPE_WRITE], STDERR_FILENO);
                    close(fds[PIPE_WRITE]);
                    close(fds1[PIPE_READ]);
                    fprintf(stderr, "game_over\n"); //ENDS CHILD
                    read(fds[PIPE_READ], buff, sizeof(buff));
                    //Will continue forever unless I put in game_over
                    close(fds1[PIPE_WRITE]);
                    close(fds[PIPE_READ]);
            }

}

1 个答案:

答案 0 :(得分:0)

这一行:

GuidedStepFragment.add(activity.fragmentManager, fragmentB.createInstance())
如果孩子退出,

将等待永久。

推荐:

read(fds[PIPE_READ], buff, sizeof(buff));