我打算在两个进程之间建立一条管道:父进程和子进程。父进程派生子进程,并使用execve将其映像替换为指定进程的映像。
父级通过std :: getline(std :: cin,input_line)从stdin中读取。 子级通过std :: cout
我正在寻找一个管道,并将子级的输出重定向到父级的输入。
问题是父级两次收到每个输入(每个输入是孩子在stdout上输出的数字)。我想解决此问题,但我不知道为什么会发生。
代码使用g ++ 7.4.0和C ++ 11标准版本进行编译。
子级被编译为名为“ p1”的二进制文件。
父代码:
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <iostream>
char *
const p1argv[] = {
(char * )
"./p1",nullptr
};
char *
const p1envp[] = {
(char * ) nullptr
};
int main(int argc,char ** argv) {
pid_t p1id;
int p1fd[2];
pipe(p1fd);
if (p1id = fork() == 0) {
close(p1fd[0]);
dup2(p1fd[1],STDOUT_FILENO);
execve(argv[0],p1argv,p1envp);
perror("Error: failed to execve ./p1.");
} else {
dup2(p1fd[0],STDIN_FILENO);
close(p1fd[1]);
std::string line;
while (std::getline(std::cin,line)) {
std::cout << "d(" << line << ")" << std::endl;
}
int status;
waitpid(p1id,& status,0);
close(p1fd[0]);
}
}
子代码:
#include <iostream>
#include <thread>
int main(int argc,char** argv) {
long it = 0;
while(true) {
it += 1;
std::cout << std::to_string(it) << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
}
}
示例代码的实际输出为:
d(d(1)) d(d(2)) ...
预期输出为:
d(1) d(2) ...