我正在实现shell,pipe和fork。我基本上是在同一父节点的两个子进程之间传递消息。个别命令的工作,但管道命令不起作用我得到错误的文件描述符。任何人都可以帮我这个吗?
以下是我的代码。
/ *分叉父* /
if ((pid = fork()) <0)
cout<<"fork error";
/ *如果是孩子* /
else if (pid == 0)
{
/* child */
if(pipe(pipeA)==-1)
cerr<<"Pipe Creation error"<<'\n';
/* Duplicating the output */
dup2(pipeA[1],1);
close(pipeA[0]);
/* Running the first command */
if(execvp(*command1,command1)<0)
{
cout<<"error in executing:"<< command<<'\n';
}
}
/ *在父母等待孩子完成* /
之前if ( (pid = waitpid(pid, &status, 0)) < 0)
cout<<"waitpid error";
/* calling method, to create second process and execute it */
secondExecute(command2);
}
// Second process will be created here
void secondExecute(char *command2)
{
if ((pid = fork()) <0)
cout<<"fork error";
else if (pid == 0)
{
dup2(pipeA[0],0);
close(pipeA[1]);
/* Executing the second process */
if(execvp(*args,args)<0)
{
cout<<"couldn't execute:"<< command2<<'\n';
}
}
if ( (pid = waitpid(pid, &status, 0)) < 0)
cout<<"waitpid error";
}
答案 0 :(得分:0)
您需要在致电fork
之前创建管道。如果父母和孩子都是pipe
他们自己,他们每个人都会创建一个不同的管道。您需要两个进程之间的共享管道。