I am building a simple shell in c using fork
and execlp
. I will be given a set of commands separated by pipes. eg: ls -l | wc -l
.
I want to use pipes for intra process communication. So the output from ls -l
is input for wc -l
. There can any number of commands separated by pipes. I am not understanding whether to create a pipe between a child process and parent and then when I get a output from a child process somehow transfer that output to another child process... I have parsed the inputs. How can I go about this?
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]);
}
}