reading and writing to another process

moss%brl-vld at sri-unix.UUCP moss%brl-vld at sri-unix.UUCP
Fri Sep 30 00:10:16 AEST 1983


From:      Gary S. Moss (301)278-6647 <moss at brl-vld>

No problem.

1)  Set up two pipes using pipe(2) one for sending to "bar"
and one for recieving from "bar".

2)  Use fork(2) to fork a process.

3)  In the child, close stdin and stdout and use fcntl(2) to rename stdin
as the read end of the first pipe, and rename stdout as the write end of
the 2nd pipe, close all open file descriptors, then execl(2) "bar".

4)  In the parent open the 1st pipe for writing using open(2) or
fdopen(3S), and open the 2nd pipe for reading.

Example:

typedef struct {
	int	rd;
	int	wr;
} Pipe;
Pipe	pipe1fd, pipe2fd;

main() {
	if( pipe( &pipe1fd ) == -1 ) {
		perror( "main()" );
		exit( errno );
	}
	if( pipe( &pipe2fd ) == -1 ) {
		perror( "main()" );
		exit( errno );
	}
	if( (pid1 = fork()) == -1 ) {
		perror( "main()" );
		exit( errno );
	} else	if( pid1 == 0 ) {
		/* C h i l d   Read from 1st pipe, write to 2nd.
		 */
		(void) close( 0 );
		(void) fcntl( pipe1fd.rd, F_DUPFD, 0 );
		(void) close( 1 );
		(void) fcntl( pipe2fd.wr, F_DUPFD, 1 );
		(void) close( pipe1fd.rd ); /* Close all open file desc. */
		(void) close( pipe1fd.wr );
		(void) close( pipe2fd.rd );
		(void) close( pipe2fd.wr );
		(void) execl( "/.../bar", "bar", 0 );
		perror( "bar" );
		exit( errno );
	}
	/* P a r e n t  write to 1st pipe, read from 2nd.
	 */
	wrPipeFp = fdopen( pipe1fd.wr, "w" );
	/* 
		.
		.
		.
		write to "bar".
		.
		.
		.
	 */
	(void) fclose( wrPipeFp );
	(void) close( pipe1fd.rd );
	(void) close( pipe2fd.wr );

	rdPipeFp = fdopen( pipe2fd.rd, "r" );
	/*
		.
		.
		.
		read from "bar".
		.
		.
		.
	*/
	(void) fclose( rdPipeFp );
	while( wait( &status ) != -1 ) /* Wait for all children.	*/
		;
	exit( 0 );
}

- Moss.



More information about the Comp.unix mailing list