【发布时间】:2016-10-07 20:57:12
【问题描述】:
我正在实现一个外壳、管道和叉子。我基本上是在同一个 parent 的两个子进程之间传递消息。单个命令的工作,但管道命令不起作用我收到错误文件描述符之类的错误。谁能帮我解决这个问题?
以下是我的代码。
/* 分叉父级 */
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";
}
【问题讨论】:
-
“谁能快速帮忙”这不是本网站的目的,抱歉。
-
没有人愿意帮助那些甚至不能正确缩进他们的代码的人,以便它实际上是可读的。如果您不想浪费精力使您的代码对其他人具有可读性,那么为什么要浪费时间来弄清楚呢?
-
您在子进程中创建的管道在父进程中将不可用。如果你想在两个进程之间进行通信,那么你需要创建管道 before 你 fork。
-
谢谢,Joachim,我做到了,这次它没有给我任何错误,但是当我运行这样的命令时 ls ||种类 。它在外壳中保持空白。
-
@user6939129 您的问题是关于错误的。如果有人回答了这个问题,而现在您遇到了不同的问题,则关键字是不同,您应该打开一个新问题。也许你会为我们在那个中格式化你的代码做体面的事情。