Path: utzoo!attcan!uunet!ncrlnk!ncrcae!ece-csc!mcnc!rutgers!mit-eddie!ll-xn!adelie!axiom!insyte!m2 From: m2@insyte.UUCP (Mike Arena) Newsgroups: comp.unix.wizards Subject: Re: How to do a pipe & fork? Message-ID: <151@insyte.UUCP> Date: 9 Nov 88 18:25:58 GMT References: Reply-To: m2@insyte.UUCP (Michael J. Arena) Organization: Innovative Systems Techniques, Newton, MA Lines: 75 In article pratt@zztop.rutgers.edu (Lorien Y. Pratt) writes: >OK, an even easier question than I posted last time, I'd really appreciate >your help. > >I have two processes that I want to communicate. I want the parent to >be able to fprintf to the child's stdin and to fscanf from the child's >stdout. ... stuff deleted ... >Here's what I have so far, which I know is wrong. ... code deleted ... > --Lori >-- >------------------------------------------------------------------- >Lorien Y. Pratt Computer Science Department >pratt@paul.rutgers.edu Rutgers University > Busch Campus >(201) 932-4634 Piscataway, NJ 08854 Here is a procedure to execute a command and creates three pipes to the child. The pid of the child is returned. The parent then can write to the child's standard input (fdin) and read from the childs standard output and error (fdout and fderr). If you need FILE pointers, then use the fdopen() function of the three file descriptors. Obviously, you should do more error checking than what I did below. Also, I used vfork() instead of fork() since an exec is done in the child immediately. Vfork() saves a lot of time and space. You will have to change the arguments for the function if you need to use execlp() or whatever instead of execvp(). int execute(name,args,fdin,fdout,fderr) char *name, *args[]; int *fdin, *fdout, *fderr; { int Pfdin[2], Pfdout[2], Pfderr[2], pid; pipe (Pfdin); pipe (Pfdout); pipe (Pfderr); switch (pid = vfork ()) { case -1: printf("vfork error"); case 0: close(0); /* Close child's stdin stream then ... */ dup(Pfdin[0]); /* make child's stdin be the first pipe */ close(1); /* Close child's stdout stream then ... */ dup(Pfdout[1]); /* make child's stdout be the second pipe */ close(2); /* Close child's stderr stream then ... */ dup(Pfderr[1]); /* make child's stderr be the third pipe */ execvp (name, args); } *fdin = Pfdin[1]; /* Parent will write to child's stdin */ *fdout = Pfdout[0]; /* Parent will read from child's stdout */ *fderr = Pfderr[0]; /* Parent will read from child's stderr */ return( pid ); } -- Michael J. Arena Innovative Systems Techniques (INSYTE) 1 Gateway Center, Newton, MA (617) 965-8450 UUCP: ...harvard!linus!axiom!insyte!m2