How to do a pipe & fork?

Lorien Y. Pratt pratt at zztop.rutgers.edu
Thu Nov 3 05:51:38 AEST 1988


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.

Here's what I have so far, which I know is wrong.

#include <netdb.h>
#include <stdio.h>
#define STRLEN 40

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

pid = fork();

if (pid == 0)   /* We are the children */
{
  /* This part works.  I tested it in its own program without being a child. */
  i = execlp("rsh", "rsh", "topaz", "/u2/ingres/bin/sql", "spam", 0);
  printf("execlp didn't work, return code is %d\n", i);
}
else
{
  printf( "Child's process ID is %d\n", pid ); fflush(stdout);
  /* Open file descriptor to talk to child.  I know it's wrong to pass a pid
     to fdopen, but how do I get the right fdes instead? */
  sql = fdopen( pid, "a+" );
  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 );
}

}

Of course, this core dumps on the fgets call, because fdopen returns
zero because I'm passing it a useless first argument.  I thought that
my best shot would help you to help me, though.

AdTHANKSvance!
   --Lori
-- 
-------------------------------------------------------------------
Lorien Y. Pratt                            Computer Science Department
pratt at paul.rutgers.edu                     Rutgers University
                                           Busch Campus
(201) 932-4634                             Piscataway, NJ  08854



More information about the Comp.unix.wizards mailing list