实时得到程序的标准输出

类别:编程语言 点击:0 评论:0 推荐:

示例程序:
/*
  Name: 3745739.c
  Copyright: iDLER FANG
  Author: iDLER FANG
  Date: 22-01-05 22:56
  Description: Sample of child process I/O redirect.
*/

#include <stdio.h>
#include <stdlib.h>

#include <windows.h>

#define BUFFSIZE    4096

int main(int argc, char *argv[])
{
    const char* lpszCmd = "test.exe";
   
    /* 以下为创建匿名管道所需的参数 */
    HANDLE  hReadPipe,  /* 读管道 */
            hWritePipe; /* 写管道 */
    SECURITY_ATTRIBUTES sec_attr; /* 安全属性 */
   
    /* 以下为创建子进程需要的参数 */
    STARTUPINFO start_info;
    PROCESS_INFORMATION proc_info;
   
    char buff[BUFFSIZE];    /* 缓冲区 */
    DWORD bytesRead;
    const int interval = 100;   /* 更新间隔 */
   
    /* 创建匿名管道 */
    sec_attr.bInheritHandle = TRUE;   /* 保证管道能够被子进程继承 */
    sec_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
    sec_attr.lpSecurityDescriptor = NULL; /* 使用系统默认的安全描述符 */   
    if (CreatePipe(&hReadPipe, &hWritePipe, &sec_attr, 0) == 0) {
        fprintf(stderr, "Anonymous pipe creation failed!\n");
        return -1;
    }
   
    /* 创建子进程 */
    start_info.cb = sizeof(STARTUPINFO);
    GetStartupInfo(&start_info);
    start_info.hStdOutput = hWritePipe; /* 重定向stdout */
    start_info.hStdError = hWritePipe;  /* 重定向stderr */
    start_info.wShowWindow = SW_HIDE;   /* 当然,不显示窗口 */
    start_info.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;    /* 使以上参数生效 */
    if (CreateProcess(NULL, TEXT(lpszCmd), NULL, NULL, TRUE, NULL, NULL, NULL, &start_info, &proc_info) == 0) {
        fprintf(stderr, "Child process creation failed!\n");
        return -1;
    }
    CloseHandle(hWritePipe); /* 当前进程并不需要这个写入端 */
   
    /* 从hReadPipe读入 */
    for(;;) {
        if (ReadFile(hReadPipe, buff, BUFFSIZE - 1, &bytesRead, NULL) == NULL) break;
        printf("%s", buff);
        Sleep(interval);               
    }

    system("PAUSE");
    return 0;
}

test.c
#include <stdio.h>
#include <stdlib.h>

#include <windows.h>

int main(int argc, char *argv[])
{
    const int times = 10;
    const int interval = 1000;
    int i;
   
    for (i = 0; i < times; i++) {
        fprintf(stdout, "i = %d\n", i);
        fflush(stdout);
        Sleep(interval);
    }

    return 0;
}

本文地址:http://com.8s8s.com/it/it23484.htm