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);
}
爲什麼功能只有正確地在第一循環的工作?之後有什麼變化?