标题不言而喻。这是功能:
void fork_and_chain(int * pipein, int * pipeout, Command *cmd, int size)
{
auto pid = fork();
int status;
if(!pid)
{
if(pipein) {
dup2(pipein[0], 0);
close(pipein[0]);
close(pipein[1]);
} else if (cmd->redirectin) {
int fin = open(cmd->filename.c_str(), O_RDONLY);
dup2(fin, 0);
close(fin);
}
if(pipeout) {
dup2(pipeout[1], 1);
close(pipeout[0]);
close(pipeout[1]);
} else if (cmd->redirectout) {
int fout = open(cmd->filename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
dup2(fout, 1);
close(fout);
}
if (execvp(cmd->args_char[0], cmd->args_char.data()) < 0) {
std::cerr << "Command not Found" << std::endl;
}
} else if (pid < 0) {
std::cerr << "Fork failed." << std::endl;
exit(1);
} else {
// waiting for child process to finish
}
}
无论我放在那里,我都会得到一个无限循环(我正在制作一个shell)。我要么无限地得到“cmd”提示,要么一无所获。链接代码继续运行,我不知道终止它。
答案 0 :(得分:1)
我认为你正在寻找waitpid()。在评论部分添加:
int status = 0;
waitpid(pid, &status, 0);
std::cerr << "child finished with status: " << status << std::endl;