Skip site navigation (1)Skip section navigation (2)
Date:      Tue, 22 Dec 1998 01:21:36 PST
From:      Michael Ryan <mike@NetworX.ie>
To:        FreeBSD Support <questions@FreeBSD.ORG>
Subject:   Mystery with pipe(), fork() and dup()
Message-ID:  <ECS9812220136A@NetworX.ie>

next in thread | raw e-mail | index | archive | help
Hi all,

This one has me completely stumped.  I wanted to write a program
which has the same effect as
	grep pattern | more
so I wrote the program listed below.  As it stands, it works
perfectly every time.

However, if I change the line which reads
	if (pid == 0)
to read
	if (pid)
it never works!  The stdio for 'more' seems to get screwed up.
Can anybody explain why it doesn't work?

Also, to my amazement, if I leave the line which reads
	if (pid == 0)
alone, but delete the line which reads
	close(fd[1]);
that is the 3rd last line of main(), it also fails to work!
Deleting the other "close(fd[n])" calls don't seem to make
any difference.

I'd be extremely grateful to anybody who can shed light on this.

The program:
----------------------------------------------------------------
#include <stdio.h>
#include <unistd.h>

#define GREP   "grep"
#define MORE   "more"

void main(int, char **);
static void error(char *);

static void error (char *msg) {
   fprintf(stderr, "Error: %s\n", msg);
   exit(1);
}

void main (int argc, char **argv) {
   int fd[2];
   pid_t pid;

   if (pipe(fd)) error("pipe() failed");
   if ((pid=fork()) < 0) error("fork() failed");
   if (pid == 0) {
      close(1);
      if (dup(fd[1]) != 1) error("dup(1) failed");
      close(fd[0]);
      close(fd[1]);
      argv[0] = GREP;
      execvp(GREP, argv);
      error("execvp(" GREP ") failed");
   }
   close(0);
   if (dup(fd[0]) != 0) error("dup(0) failed");
   close(fd[0]);
   close(fd[1]);
   execlp(MORE, MORE, 0);
   error("execlp(" MORE ") failed");
}
----------------------------------------------------------------


Thanks for any help.

Bye,
Mike
mike@NetworX.ie
www.NetworX.ie
---




To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?ECS9812220136A>