I'm trying to create a simple shell that supports pipes and file redirects. Here's the execute function I came up with so far:
void execute(std::vector<Command *> cmds)
{
int inp[2], out[2];
pipe(inp);
pipe(out);
int status, fd = 0;
for (auto cmd : cmds)
{
auto pid = fork();
if (pid == -1) {
throw std::runtime_error("Could not fork.");
} else if (pid == 0) {
dup2(inp[1], 1);
if (cmd->redirectout) {
fd = fileno(fopen(cmd->filename.c_str(), "w"));
dup2(1, fd);
}
dup2(out[0], 0);
if (cmd->redirectin) {
fd = fileno(fopen(cmd->filename.c_str(), "r"));
dup2(0, fd);
}
close(inp[0]);
close(inp[1]);
close(out[0]);
close(out[1]);
if(execvp(cmd->args_char[0], cmd->args_char.data()) < 0) {
std::cout << "Command not found." << std::endl;
exit(1);
}
} else {
dup2(out[0], inp[0]);
dup2(out[1], inp[1]);
close(inp[0]);
close(inp[1]);
close(out[0]);
close(out[1]);
while (wait(&status) != pid);
}
}
}
When I execute this the program is running but nothing happens. I've been working on this function for days but can't seem to understand the reason. I think the parent process is waiting forever for the child. Can somebody please help me with this?