我需要從C++應用程序中運行外部程序。我需要該程序的輸出(我想在程序仍在運行時看到它),並且還需要輸入。C++外部程序IO
什麼是重定向IO的最好和最優雅的方式?它是否應該在自己的線程中運行?任何例子?
它在OSX上運行。
我實現這樣的:
ProgramHandler::ProgramHandler(std::string prog): program(prog){
// Create two pipes
std::cout << "Created Class\n";
pipe(pipe1);
pipe(pipe2);
int id = fork();
std::cout << "id: " << id << std::endl;
if (id == 0)
{
// In child
// Close current `stdin` and `stdout` file handles
close(fileno(stdin));
close(fileno(stdout));
// Duplicate pipes as new `stdin` and `stdout`
dup2(pipe1[0], fileno(stdin));
dup2(pipe2[1], fileno(stdout));
// We don't need the other ends of the pipes, so close them
close(pipe1[1]);
close(pipe2[0]);
// Run the external program
execl("/bin/ls", "bin/ls");
char buffer[30];
while (read(pipe1[0], buffer, 30)) {
std::cout << "Buf: " << buffer << std::endl;
}
}
else
{
// We don't need the read-end of the first pipe (the childs `stdin`)
// or the write-end of the second pipe (the childs `stdout`)
close(pipe1[0]);
close(pipe2[1]);
// Now you can write to `pipe1[1]` and it will end up as `stdin` in the child
// Read from `pipe2[0]` to read from the childs `stdout`
}
}
但作爲輸出我得到這個:
創建
類ID:84369
ID:0
我不明白爲什麼它被稱爲兩次,爲什麼它不會第一次分叉。我在做什麼/理解錯誤。
Windows或Linux或OSX或其他? –
Sry忘記了:這是OSX –