Redirecting Standard I/O for Child Processes

An application can use unnamed pipes to redirect the standard input and the standard output for a child process.

A typical use of an unnamed pipe is to read the output of a child process. An application creates a pipe and then duplicates the standard output handle. When the child process is started, its standard output will be written into the pipe, where the application can read and display it. The following code fragment shows how to do this:

    #define INCL_DOSPROCESS
    #define INCL_DOSNMPIPES

    #include <os2.h>

    #define PIPESIZE 256
    #define HF_STDOUT 1      /* Standard output handle */

    HPIPE hpR, hpW;
    RESULTCODES resc;
    ULONG ulRead, ulWritten;
    CHAR achBuf[PIPESIZE],
         szFailName[CCHMAXPATH];

    HFILE hfSave = -1,
          hfNew = HF_STDOUT;

    DosDupHandle(HF_STDOUT,
                 &hfSave); /* Saves standard output handle      */

    DosCreatePipe(&hpR,
                  &hpW,
                  PIPESIZE); /* Creates pipe                      */

    DosDupHandle(hpW,
                 &hfNew); /* Duplicates standard output handle */


    DosExecPgm(szFailName,
               sizeof(szFailName), /* Starts child process      */
               EXEC_ASYNC,
               (PSZ) NULL,
               (PSZ) NULL,
               &resc,
               "DUMMY.EXE");

    DosClose(hpW);                /* Closes write handle to ensure     */
                                  /* Notification at child termination */

    DosDupHandle(hfSave,
                 &hfNew);     /* Brings stdout back                */

    /*
     * Read from the pipe and write to the screen
     * as long as there are bytes to read.
     *
     */

    do {
        DosRead(hpR,
                achBuf,
                sizeof(achBuf),
                &ulRead);

        DosWrite(HF_STDOUT,
                 achBuf,
                 ulRead,
                 &ulWritten);

    } while(ulRead);

A parent process can also use unnamed pipes to communicate with a child process by redirecting both the standard input and the standard output for the child process. To do this, the parent process:

The parent process controls the meanings for standard I/O for the child process. Thus, when the child process uses standard I/O handles with DosRead and DosWrite, it reads from and writes to the pipes of its parent instead of reading from the keyboard and writing to the display.


[Back: Reading from and Writing to Unnamed Pipes]
[Next: Using Named Pipes]