Dissimilar Program Interaction? (sorry, long)

Rob Gardner rdg at hpfclj.HP.COM
Wed Oct 8 04:44:37 AEST 1986


> > Unfortunately I don't know how to
> > connect the pipe(s) to standard input and standard output
> > of the sub-program.
> > Also this does not permit fscan and fprint.
> 
> 	int fildes[2];
> 	int pid;
> 	int c;
>  
> 	pipe (fildes);
> 
> 	if( (pid = fork()) == 0 )
> 	{
> 	/* CHILD */
> 
> 	    close(0);
>    	    dup (fildes[0]);		/* Redirect stdin of child from parent*/
> 	    close(1);
>    	    dup (fildes[1]);		/* Redirect stdout of child to parent */
> 
> 	    close (fildes[0]);		/* Don't need these anymore */
> 	    close (fildes[1]);
> 
> 	    exec_ (the_child);
> 	    /* 
> 	     * Now when the child writes to its file descriptor 1, it is 
> 	     * actually going down the pipe's write end. Likewise its read
> 	     * on file descriptor 0 is actually reading from the read end of
> 	     * the pipe.
> 	     */
> 	}


Be warned: the above code does NOT work. Pipes are unidirectional, and you
need two of them to do what you want. The above code runs a program with
its stdout connected to its stdin! What you really want is something like:

	int input[2], output[2];
	pipe(input);	/* parent reads 0, child writes 1 */
	pipe(output);	/* parent writes 1, child reads 0 */
	if (fork() == 0) {
		close(0);
		dup(output[0]);
		close(1);
		dup(input[1]);
		close(output[1]);
		close(input[0]);
		exec...
	}
	close(output[0]);
	close(input[1]);
	/* now reads on input[0] will read stuff output by child,
	   and writes on output[1] will be read by child. another
	   neat thing is that when the child dies, the reads will
	   fail inthe parent, and the writes will produce SIGPIPE */


Rob Gardner                     {ihnp4,hplabs,hpbbn}!hpfcla!rdg
Hewlett Packard                 or rdg%hpfcla at hplabs.hp.com
Fort Collins, Colorado          303-229-2048



More information about the Comp.unix mailing list