2014-05-06 18 views
9

cmd_moreCome passare STDIN al processo figlio?

void WriteToPipe(void) 

// Read from a file and write its contents to the pipe for the child's STDIN. 
// Stop when there is no more data. 
{ 
    DWORD dwRead, dwWritten; 
    CHAR chBuf[BUFSIZE]; 
    BOOL bSuccess = FALSE; 
    char * name = malloc(100); 


fgets(name, 100, stdin); 


    bSuccess = WriteFile(g_hChildStd_IN_Wr, name, 10, &dwWritten, NULL); 
    if (!bSuccess) 
     ErrorExit(""); 

} 

void ReadFromPipe(void) 

// Read output from the child process's pipe for STDOUT 
// and write to the parent process's pipe for STDOUT. 
// Stop when there is no more data. 
{ 
    DWORD dwRead, dwWritten; 
    CHAR chBuf[BUFSIZE]; 
    BOOL bSuccess = FALSE; 
    HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE); 


    bSuccess = ReadFile(g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRead, NULL); 
    if (!bSuccess || dwRead == 0) 
     return 100; 

    bSuccess = WriteFile(hParentStdOut, chBuf, 
     dwRead, &dwWritten, NULL); 
    if (!bSuccess) 
     return 101; 

} 

Il principale (non completo):

while (1) 
{ 
    Sleep(500); 

    ReadFromPipe(); 

    WriteToPipe(); 


} 

Sto cercando di aprire il cmd come un processo figlio e di passare l'ingresso padre al STDIN flusso bambino, e che a stampa lo STDOUT del bambino.

Come potete vedere, funziona alla prima volta ma poi ho capito "altro?" indietro dal processo figlio (il cmd) e poi rimane bloccato in attesa dell'output.

Perché sto ricevendo questo "di più?" indietro?

Che cos'è "altro?"

+1

Hmm, provare ad ottenere l'handle di output standard ONCE a livello globale. Inoltre, evita di dormire e usa un mutex, in modo che il file, che usi impropriamente come pipe, sia scritto in modo sicuro prima di leggere/leggere in modo sicuro prima di essere nuovamente scritto). E usa il debugger. C'è in qualche modo una porzione di risposta a qualsiasi comando che hai superato, che termina con "Altro?" Quindi potresti avere problemi di memoria ai limiti, sovrascrivendo alcune cose. – icbytes

risposta

2

L'unico modo per il reindirizzamento dell'input genitore che ho trovato è la creazione di un thread aggiuntivo. L'algoritmo comune è:

  1. Creare pipe - (hPipeRead, hPipeWrite)
  2. Creare processo figlio con standard input - hPipeRead
  3. creare un nuovo thread nel processo genitore che sta leggendo GetStdHandle(STD_INPUT_HANDLE) e sta scrivendo buffer di lettura a hPipeWrite subito. Il thread è completato quando stdInput è finito.
  4. processo genitore aspetta filo supplementare

questo modo è descritto in Microsoft support article.

Problemi correlati