Problem with pipe/fork

Michael Corbett corbettm at cutmcvax.cutmcvax.cs.curtin.edu.au
Wed Apr 17 18:21:40 AEST 1991


gaumondp at JSP.UMontreal.CA (Gaumond Pierre) writes:

>The following program creates a pipe and generates two processes with fork. The
>parent reads data from standard input and writes it to the pipe. The child
>reads the pipe and writes data to the standard output.

>Quite simple. However, it doesn't work.

>The program reads all the data and everything is transfered (I have tried a
>small file as a redirection of input). The processes block after the last
>character is transfered to the standard output. The processes seem to wait for
>something... for what? EOF?

>I understood that the "fclose" on the write end of the pipe would generate an
>EOF status at the read end. Is it correct. Perhaps the problem is somewhere
>else...

This is partially correct... The EOF is not sent to the pipe until all the
file descriptors have have closed in every process... due to the fork there
are 2 file descriptors (one in each process) associated with the write end
of the pipe.... So these both need to be closed before the loop in the 
child process

For neatness you should also close the read end of the pipe in the 
parent process...

I have added the appropriate lines in the code below... (Hope it helps)

>-------------------------------------------------------------------------------
><necessary include files>

>main()
>{
>  FILE *fp;
>  int fdi[2];
>  char c;
>  
>  pipe(fdi);
>  if (fork()!=0)
>  { /* parent */
     close (fdi[0]);
>    fp=fdopen(fdi[1],"w");
>    for (c=getchar(); !feof(stdin); c=getchar()) fputc(c,fp);
>    fclose(fp);
>    wait(0);
>  }
>  else
>  { /* child */
     close (fdi[1]);
>    fp=fdopen(fdi[0],"r");
>    for (c=fgetc(fp); !feof(fp); c=fgetc(fp)) putchar(c);
>    fclose(fp);
>  }
>}

--

>>           Michael Corbett             | "Last night, I thought my arm was <<
>> corbettm at anger.cipal.cs.curtin.edu.au | hanging out of bed.  So I got out <<
>> corbettm at cutmcvax.cs.curtin.edu.au    | to push it in."                   <<



More information about the Comp.sys.sgi mailing list