Windows - Looking for a complete example, C++ anonymous pipe transfers data between parent and child processes!
黄舟
黄舟 2017-05-16 13:20:54
0
1
926

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.

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
迷茫
#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;
}

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!