PRB: Spawn Does Not Pass Redirection to Child

ID Number: Q38308

5.10 6.00 6.00a 6.00ax 7.00 | 5.10 6.00 6.00a

MS-DOS | OS/2

Summary:

SYMPTOMS

Using the program below to spawn SORT.EXE, the "sort" apparently

starts, but does nothing. The behavior is similar to starting

"sort" from the MS-DOS prompt without any arguments.

CAUSE

Because COMMAND.COM, and NOT the EXEC loader, handles indirection,

this is the expected behavior. Child processes inherit the handles

of their parents; therefore, to redirect the input and output of

the child, first change the definitions of STDIN and STDOUT in the

parent process.

RESOLUTION

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. Note: The dup and dup2 functions in the C version 5.1

run-time library are the same as the Interrupt 21h functions 45h

and 46h, respectively.

There also are partial examples of this technique on page 230 of

the "Microsoft C Run-Time Library Reference" for version 5.1 and on

page 353 of "Advanced MS-DOS Programming" (by Duncan, published by

Microsoft Press).

It is possible to use freopen() to redefine STDIN and STDOUT;

however, doing so loses any redirection that may have been

performed on the parent process.

The easiest workaround is to use the system function to spawn a

copy of COMMAND.COM that runs SORT.EXE, as follows:

system("sort.exe <infile.dat >outfile.dat");

More Information:

The following code sample demonstrates the problem.

Sample Code

-----------

/* Compile options needed: none

*/

#include <stdio.h>

#include <process.h>

main()

{

char *args[6] ;

args[0] = "sort" ;

args[1] = "<" ;

args[2] = "infile.dat" ; /* exists */

args[3] = ">" ; /* direct output to a disk file */

args[4] = "outfile.dat" ;

args[5] = NULL ;

spawnvp (P_WAIT, "sort.exe", args) ;

}

Additional reference words: 5.00 5.10 6.00 6.00a 6.00ax 7.00