-2

I am implementing a shell , pipe, and fork. I am basically passing messages between two child processes of the same parent . Individual command's work but pipe commands don't work I get errors like bad file descriptors . Can anyone help me with this ?

Following is my code .

/* Forking the parent */

if ((pid = fork()) <0)

cout<<"fork error";

/* If it is a child */

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';  

}

}

/* In the parent waiting till the child completes */

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";   

}    
Sumanth
  • 363
  • 3
  • 17
  • _"Can someone quickly help"_ That's not the purpose of the site, sorry. – πάντα ῥεῖ Oct 07 '16 at 21:00
  • Nobody will want to help anyone who can't even properly indent their code, so that it's actually readable. If you don't want to waste the effort to make your code readable to others, why should anyone waste their time figuring it out? – Sam Varshavchik Oct 07 '16 at 21:08
  • The pipe you create in the child process will not be available in the parent process. If you want communication between the two processes then you need to create the pipe *before* you fork. – Some programmer dude Oct 07 '16 at 21:09
  • Thanks, Joachim , i did that , it doesn't give me any error this time but when i run a command like this ls || sort . it stays blank in the shell . – Sumanth Oct 07 '16 at 21:59
  • @user6939129 Your question is about an error. If someone answered that question and now you have a different problem the key word is *different* and you should open a new question. And maybe you'll do us the decency of formatting your code in that one. – kfsone Oct 07 '16 at 22:07

1 Answers1

0

You need to create the pipe before you call fork. If the parent and child each all pipe themselves, they'll each create a different pipe. You want a shared pipe between the two processes.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278