2
我想创建一个函数,它运行一个命令,然后将输出管道输出到第二个命令并运行它。我在无限循环中运行该函数。问题是,该函数首次运行,但之后没有显示任何内容。 例如,当我运行ls | wc -l
时,它第一次显示正确的结果,但是当我运行它之后,我得不到输出。使用fork和exec管道输出后不显示输出
这里是我的功能(解析是另一个函数处理):
void system_pipe(std::string command1, std::string command2)
{
int status;
int fd[2];
int fd2[2];
pipe(fd);
int pid = fork();
// Child process.
if (pid == 0)
{
std::shared_ptr<char> temp = string_to_char(command1);
char *name[] = {"/bin/bash", "-c", temp.get(), NULL};
close(fd[0]);
dup2(fd[1], 1);
execvp(name[0], name);
exit(EXIT_FAILURE);
}
// Parent process.
else
{
std::shared_ptr<char> temp = string_to_char(command2);
char *name[] = {"/bin/bash", "-c", temp.get(), NULL};
close(fd[1]);
dup2(fd[0], 0);
waitpid(pid, &status, 0);
//my_system(command2);
// Fork and exec a new process here.
int pid2 = fork();
if (pid2 == 0)
{
execvp(name[0], name);
exit(EXIT_FAILURE);
}
else
{
waitpid(pid2, NULL, 0);
}
}
if (status)
std::cout << "Bad" << std::endl;
}
我这样调用该函数:
while(true)
{
string line;
getline(cin, line);
pair<string, string> commands = parse(line);
system_pipe(commands.first, commands.second);
}
为什么功能只有正确地在第一循环的工作?之后有什么变化?