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

admin2025-04-04  0

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?

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1743736746a216878.html

最新回复(0)