How to do a pipe & fork?

Keith Pyle keith at execu.UUCP
Fri Nov 4 01:47:04 AEST 1988


In article <Nov.2.14.51.36.1988.8260 at zztop.rutgers.edu> pratt at 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.  I know that I need to fork and then in the child do an execlp,
>but I can't figure out how to set up the file descriptors so I can do
>what I want. The Sun IPC guide does not help me here.  I know that I
>need to do a dup and a fork and a pipe, but I'm not sure in what order
>and with what parameters.
>
> [code deleted...]

Here's a quickly hacked version of the code Lorien posted that illustrates
setting up a pipe:

#include <stdio.h>

main()
{
int pid;
FILE *fdopen();
FILE *sql;
char from_sql[256];
char *fgets();
int i;
int filedes[2];

pipe(filedes);
pid = fork();

if (pid == 0)   /* We are the children */
{
  close(1);
  i = dup(filedes[1]);
  i = execlp("rsh", "rsh", "mesquite", "cat /usr/keith/bin/chkmail", 0);
  printf("execlp didn't work, return code is %d\n", i);
}
else
{
  printf( "Child's process ID is %d\n", pid ); fflush(stdout);
  sql = fdopen( filedes[0], "r" );
  printf( "result of fdopen is %d\n", sql ); fflush(stdout);

  /* Start talking to child */
  fgets(from_sql, 256, sql );
  printf("SQL says: %s\n", from_sql );

  fclose( sql );
}

}

The basic problem was that you need to call pipe(2) prior to fork(2) and
then dup(2) the 'write' file descriptor to be the stdout of the child
process.  For the parent, you need to call fdopen(3s) with the file descriptor
for reading created by pipe(2). Note also that the mode supplied to fdopen(3s)
must match the with which the file descriptor was created.  In the example
code by Lorien, the mode was "a+".

-----------------------------------------------------------------------------
Keith Pyle   ...!{rutgers | tut.cis.ohio-state.edu}!cs.utexas.edu!execu!keith

Disclaimer: What??  You actually believed me?
-----------------------------------------------------------------------------



More information about the Comp.unix.wizards mailing list