Home  >  Q&A  >  body text

Windows - Looking for a complete example, C++ anonymous pipe transfers data between parent and child processes!

I have found a lot of articles on the Internet that introduce pipelines, but the codes posted are either fragments, or even the spelling is full of errors. I hope some master can help me write a complete and simple example so that I can refer to it and learn.
The effect I want to achieve: the main program creates a child process and executes another exe program. The parent process transmits a byte array to the child process through an anonymous pipe, and the child process receives the data for processing. Both programs are C++ programs. Runs on windows.

黄舟黄舟2733 days ago961

reply all(1)I'll reply

  • 迷茫

    迷茫2017-05-16 13:22:54

    #include <Windows.h>
    #include <iostream>
    
    int main()
    {
        auto numArgs = 0;
        CommandLineToArgvW(GetCommandLineW(), &numArgs);
    
        if (numArgs > 1) {
            std::cout << "我是子进程" << std::endl;
            CHAR szBuffer[16]{ 0 };
            ReadFile(GetStdHandle(STD_INPUT_HANDLE), szBuffer, sizeof(szBuffer), nullptr, nullptr);
            std::cout << szBuffer << std::endl;
        }
        else {
            std::cout << "我是父进程" << std::endl;
    
            SECURITY_ATTRIBUTES sa{ 0 };
            sa.nLength = sizeof(sa);
            sa.bInheritHandle = TRUE;
    
            HANDLE hRead;
            HANDLE hWrite;
            CreatePipe(&hRead, &hWrite, &sa, 0);
    
            STARTUPINFOW si{ 0 };
            si.cb = sizeof(si);
            si.hStdInput = hRead;
            si.dwFlags = STARTF_USESTDHANDLES;
    
            PROCESS_INFORMATION pi{ 0 };
    
            WCHAR szCommand[512]{ 0 };
            GetModuleFileNameW(nullptr, szCommand, _countof(szCommand));
            wcscat(szCommand, L" test");
            CreateProcessW(nullptr, szCommand, nullptr, nullptr, TRUE, CREATE_NEW_CONSOLE, nullptr, nullptr, &si, &pi);
            WriteFile(hWrite, "hello", 5, nullptr, nullptr);
        }
    
        system("pause");
        return 0;
    }

    reply
    0
  • Cancelreply