c - Printf output only appears after program exit - Stack Overflow

I have a program called "parent" which executes another program called "child", the

I have a program called "parent" which executes another program called "child", the child only prints a message every 5 seconds then exits. The idea is to redirect the output of the child to the parent, so I create a pipeline before calling the child.

This is the parent:

int main(int argc, char *argv[])
{
    HANDLE readPipe, writePipe;
    SECURITY_ATTRIBUTES sa = {0};
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = TRUE;

    BOOL success = CreatePipe(&readPipe, &writePipe, &sa, 0);

    STARTUPINFO si = {0};
    si.cb = sizeof(STARTUPINFO);
    si.dwFlags = STARTF_USESTDHANDLES;
    si.hStdInput = INVALID_HANDLE_VALUE;
    si.hStdOutput = writePipe;
    si.hStdError = writePipe;

    PROCESS_INFORMATION processInfo = {0};
    CreateProcess(
            "path/to/child/program",
            NULL,
            NULL,
            NULL,
            TRUE,
            0,
            NULL,
            NULL,
            &si,
            &processInfo);

    char buf[2600];
    DWORD dw;
    for( ; ; ){
        if(ReadFile(readPipe, buf, sizeof(buf), &dw, NULL)){
            WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, dw, &dw, NULL);
        }
        else
            break;
    }
    return 0;
}

And this is the child:

int main(int argc, char *argv[])
{
    for(int i = 0; ; ){
        char message[] = "This is a message from the child process.\r\n";
        printf("%s", message);
        i++;
        Sleep(1000);
        if(i == 5){
            break;
        }
    }
}

This is the output:

This is a message from the child process.
This is a message from the child process.
This is a message from the child process.
This is a message from the child process.
This is a message from the child process.

It is correct, but it always shows in the parent screen AFTER the child terminates and not while it is being executed, why?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743736745a4498398.html

相关推荐

  • c - Printf output only appears after program exit - Stack Overflow

    I have a program called "parent" which executes another program called "child", the

    6天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信