【发布时间】:2014-03-02 18:53:58
【问题描述】:
我正在使用fork 和execlp 在c 中构建一个简单的shell。我将得到一组用管道分隔的命令。例如:ls -l | wc -l .
我想使用管道进行进程内通信。所以ls -l 的输出是wc -l 的输入。可以有任意数量的由管道分隔的命令。我不明白是否在子进程和父进程之间创建一个管道,然后当我从子进程获得输出时,以某种方式将该输出传输到另一个子进程......我已经解析了输入。我该怎么办?
void excueteCommands() {
int i, j;
int fd[2];
int cid1;
commandNode* ptr = head;
while (ptr != NULL) {
for (i = 0; i <= pipeCount; i++) {
cid1 = fork();
if (!cid1) {
if (i != 0) {
dup2(fd[i - 1][0], 0);
}
if (i != pipeCount) {
dup2(fd[i][1], 1);
}
for (j = 0; j < pipeCount; j++) {
close(fd[j][0]);
close(fd[j][1]);
}
execlp(ptr->command, ptr->args, NULL);
exit(0);
}
ptr = ptr->next;
}
}
for (i = 0; i < pipeCount; i++) {
close(fd[i][0]);
close(fd[i][1]);
}
}
【问题讨论】:
-
检查此页面右侧的所有“相关”问题。也许其中一些已经涵盖了您的要求。
标签: c