实时得到程序的标准输出

示例程序:
/*
  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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值