UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2008-05-04 11:18 AM

yurii
Member
Registered: 2005-07-27
Posts: 20

Re: a pipe between two childs

i'm trying to write a simple shell, but have stuck, with the following problem:
there's two child processes (child1 and child2)+ parent process..

parent process creates a pipe for these childs.
chiild1 runs exec and "redirects" its stdout to pipe write end, and child2 captures its input (child1's output) in the read end.

but the child2, i think so, stucked at the reading from pipe.
but if i replace the code

if((cpid2 = fork())<0){perror("fork(2)"); exit(0);}
      if(cpid2==0){


to

else{


everything works fine.
what is my mistake?

/// includes
int	ccpipe[2];

int main(void){
    pid_t	cpid1,cpid2;
    
    if(pipe(ccpipe)<0){	perror("pipe(2)"); exit(0); }


    if((cpid1 = fork())<0){perror("fork(2)"); exit(0);}
    if(cpid1==0){
	    close(ccpipe[READ_FD]);

 	    close(1);
	    dup2(ccpipe[WRITE_FD],1);
	    close(ccpipe[WRITE_FD]);

	    execlp("cat","cat","a",NULL);
	    perror("CHILD1 - execlp(2)");
	    exit(0);
    }
      if((cpid2 = fork())<0){perror("fork(2)"); exit(0);}
      if(cpid2==0){
	    close(ccpipe[WRITE_FD]);


 	    close(0);
	    dup2(ccpipe[READ_FD],0);
	    close(ccpipe[READ_FD]);

	    execlp("wc","wc",NULL);
	    perror("CHILD1 - execlp(2)");

	    exit(0);
    }


    waitpid(-1,NULL,0);
    waitpid(-1,NULL,0);
    return 0;
}

Offline

#2 2008-05-04 06:03 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: a pipe between two childs

Your parent process needs to close its reference to the pipe FDs as well, after
fork()'ing both children...  Prior to the waitpid() calls, add a close() of both pipe FDs...

Offline

Board footer

Powered by FluxBB