親プロセスが、子プロセスの printf 出力を都度 Read できない

実現したいこと

親プロセスが、子プロセスの printf 出力を都度 Read できるようにしたい

前提

「コマンド・プロンプト」アプリは、 printf 出力を都度表示している

発生している問題・エラーメッセージ

添付のサンプルプログラムでは、子プロセスの終了時に、まとめて Read される

該当のソースコード

C++

1// hello_world.cpp2//3#include <stdio.h>4#include <windows.h>5 6int main(void)7{8 int n = 8;9 for (int k = 0; k < n; ++k)10 {11 printf("[%d/%d] Hello, world!\n", k, n);12 Sleep(1000);13 }14 15 return 0;16}17 18// parent.cpp19//20int main(void)21 char* pcmd = (char*)"<path to>\\hello_world";22 23 HANDLE hpipe_read;24 HANDLE hpipe_write;25 SECURITY_ATTRIBUTES sa;26 sa.nLength = sizeof(sa);27 sa.bInheritHandle = TRUE;28 sa.lpSecurityDescriptor = NULL;29 30 CreatePipe(&hpipe_read, &hpipe_write, &sa, 0);31 32 STARTUPINFO si;33 PROCESS_INFORMATION pi;34 ZeroMemory(&si, sizeof(si));35 ZeroMemory(&pi, sizeof(pi));36 si.cb = sizeof(si);37 si.dwFlags = STARTF_USESTDHANDLES;38 si.hStdOutput = hpipe_write;39 si.hStdError = hpipe_write;40 41 CreateProcess(NULL, pcmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);42 43 HANDLE childProcess = pi.hProcess;44 CloseHandle(pi.hThread);45 46 char buff[1024];47 DWORD lenPeek = 0;48 DWORD lenRead = 0;49 bool bloop = true;50 while (bloop)51 {52 if (WaitForSingleObject(childProcess, 0) == WAIT_OBJECT_0)53 {54 bloop = false;55 }56 PeekNamedPipe(hpipe_read, NULL, 0, NULL, &lenPeek, NULL);57 if (lenPeek)58 {59 ReadFile(hpipe_read, buff, sizeof(buff), &lenRead, NULL);60 }61 }62 63 CloseHandle(pi.hProcess);64 CloseHandle(hpipe_write);65 CloseHandle(hpipe_read);66 67 buff[lenRead] = '\0';68 printf(buff);69 return 0;70}

試したこと

リダイレクトされた入出力を使用した子プロセスの作成

補足情報(FW/ツールのバージョンなど)

Visual Studio 2019

コメントを投稿

0 コメント