INF: How to Redirect the Input and Output of a Child Process

ID Number: Q37200

5.10 6.00 6.00a 6.00ax 7.00

MS-DOS

Summary:

The following command can be used to start up a program named SORT,

and redirect input from INFILE and output from OUTFILE:

system( "SORT < INFILE > OUTFILE" );

This command does take up extra memory for another copy of

COMMAND.COM. This behavior should not be a problem, unless you are

short on available memory. Another alternative is to redirect STDIN

and STDOUT in the parent process.

More Information:

Child processes inherit the handles of their parents; therefore, to

redirect the input and output of the child, change the definitions of

STDIN and STDOUT in the parent process. The proper way to redirect

input for a filter is described starting on page 441 of the "MS-DOS

Encyclopedia," along with a complete MASM example. The same result is

achieved in C by

1. The parent uses DUP to create duplicates of STDIN and STDOUT.

2. The parent opens or creates the files (or devices) that the child

will use for input and output.

3. The parent uses DUP2 to force its own STDIN and STDOUT to the

handles created in step 2.

4. The parent uses spawn or exec to load and run the child.

5. The parent uses the duplicate handles created in step 1 to restore

the original input and output handles.

Sample Code:

------------

/* Compile options needed: none

*/

#include <stdio.h>

#include <process.h>

#include <io.h>

#include <fcntl.h>

#include <sys\types.h>

#include <sys\stat.h>

void main( )

{

int hstdin, hstdout; /* handles to STDIN, STDOUT */

int oldstdin, oldstdout; /* duplicates of original STDIN, STDOUT */

int myin, myout; /* new STDIN, STDOUT */

hstdin = fileno( stdin ); /* step 1 */

hstdout = fileno( stdout );

oldstdin = dup( hstdin );

oldstdout = dup( hstdout );

myin = open( "infile", O_RDONLY ); /* step 2 */

myout = open( "outfile", O_CREAT | O_WRONLY );

puts( "Redirecting STDIN and STDOUT\n" ); /* step 3 */

dup2( myin, hstdin );

dup2( myout, hstdout );

spawnl( P_WAIT, "sort", NULL ); /* step 4 */

puts( "\nRestoring STDIN and STDOUT\n" ); /* step 5 */

fflush( stdout ); /* flush before restoring */

dup2( oldstdin, hstdin );

dup2( oldstdout, hstdout );

puts( "\nSTDIN and STDOUT restored.\n" );

}

Additional reference words: 5.10 6.00 6.00a 6.00ax 7.00