使用管道在C中的父项和多个子项之间进行2路通信

时间:2017-09-27 22:31:45

标签: c linux

我在尝试使管道正常通信时遇到问题。  任何帮助将不胜感激。在for循环中,我有设置:

else if (pid == 0) { //child
    close(pipes[i][TOCHILD][1]);
    dup2(pipes[i][TOCHILD][0], 0);
    close(pipes[i][TOCHILD][0]);
    close(pipes[i][FROMCHILD][0]);
    dup2(pipes[i][FROMCHILD][1], 1);
    close(pipes[i][FROMCHILD][1]);
    //exec
    ...
    execvp(args[0], args);
    exit(0);
} else { //parent
    close(pipes[i][TOCHILD][0]);
    dup2(pipes[i][TOCHILD][1], 1);
    close(pipes[i][TOCHILD][1]);
    close(pipes[i][FROMCHILD][1]);
    dup2(pipes[i][FROMCHILD][0], 0);
    close(pipes[i][FROMCHILD][0]);
}

然后我有我想读的方式:

for (int i = 0; i < numPlayers; i++) {
    char buff[10];
    read(pipes[i][FROMCHILD][0], buff, sizeof(buff));
    fprintf(stderr, "read %s\n", buff);
}

在孩子我现在发送这个:

printf("!");
fflush(stdout);

0 个答案:

没有答案