【发布时间】:2011-02-21 12:41:30
【问题描述】:
我尝试将父进程的标准输入转移到子进程。
stdin --> 父进程 --> child_eingabe[1] --> child_eingabe[0] --> 子进程 --> stdin
我的小程序以这种方式工作,我可以将父进程中的内容写入管道(使用 write() 命令),并通过标准输入到达我的孩子。不起作用的是,父级的标准输入直接写入管道中。这是否按我的计划工作?
#include <iostream>
#include <string>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main(int argc, char *argv[])
{
// string to the client
string sClient = "/tmp/myecho";
int child_eingabe[2];
cout << "Creating pipes " << endl;
if(pipe(child_eingabe) < 0) {
cout << " Error in pipe " << endl;
}
// forking now
pid_t pid;
cout << "Forking process" << endl;
if((pid = fork()) == 0) {
close(child_eingabe[1]);
int fid = -1;
if(fid=dup2(child_eingabe[0], 0) < 0)
cout << "Could not redirect STDIN" << endl;
close(child_eingabe[0]);
int result = execve(sClient.c_str(),0,0);
cout << "something went wrong while starting client" << endl;
if (result != 0) {
cout << "Could not start" << endl;
}
exit(0);
}
close(child_eingabe[0]);
// if(dup2(0,child_eingabe[1]) < 0)
if(dup2(child_eingabe[1],0) < 0)
cout << "Could not redirect STDIN" << endl;
close(0);
while(1)
{
sleep(1);
}
return 0;
}
如果我正确地看到了所有内容,那么父部分中的第二个 dup2 不会像我预期的那样。
【问题讨论】: