我在尝试使管道正常通信时遇到问题。 任何帮助将不胜感激。在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);