[comp.unix.questions] Unix doesn't work !

randy@retix.retix.COM (Miyazaki Randy) (03/24/89)

Why does the child read not terminate with a End of File indication ?
Bizzarely enough, the program hangs both under BSD 4.3 and
S5R3 (Interactive VP/IX 1.0.6). This seems to contradict any
documentation on pipes I have seen.

int pipefd[2];
char buf;

main()
{
  int len;
  
  if (pipe(pipefd) < 0)
    {
      perror("pipe");
      exit(1);
    }
  if (fork())
    {
      /* Parent process here */
      printf("reading...\n");
      len = read(pipefd[0], &buf, 1);
      printf("child read return %d\n", len);
      if (len < 0)
	perror("read");
      exit(0);
    }
  sleep(2);
  printf("child process exiting, parent read should return EOF\n");
  exit(0);
}

kucharsk@uts.amdahl.com (William Kucharski) (03/25/89)

In article <407@retix.retix.COM> randy@retix.retix.com.UUCP (Miyazaki Randy) writes:
 >Why does the child read not terminate with a End of File indication ?
 >Bizzarely enough, the program hangs both under BSD 4.3 and
 >S5R3 (Interactive VP/IX 1.0.6). This seems to contradict any
 >documentation on pipes I have seen.
 >
Although it's not mentioned in the man page, you should close the file
descriptor you are _not_ using on your end of the pipe (i.e., if you are the
parent, close pipefd[1]; if you're the child, close pipefd[0].)  If you change
your code from

 >      len = read(pipefd[0], &buf, 1);

to
	close(pipefd[1]);
        len = read(pipefd[0], &buf, 1);

it does work...
-- 
					William Kucharski

ARPA: kucharsk@uts.amdahl.com
UUCP: ...!{ames,decwrl,sun,uunet}!amdahl!kucharsk

Disclaimer:  The opinions expressed above are my own, and may not agree with
	     those of any other sentient being, not to mention those of my 
	     employer.  So there.