如何从一个Windows控制台应用程序向另一个发送消息?

问题描述:

我有一个Windows控制台应用程序,可以启动子进程. 如何向子进程发送消息? 我发现了 PostMessage()之类的函数/PeekMessage()-这就是我所需要的,但是据我了解,它在一个应用程序中使用,并使用HWND标识目标窗口(我在应用程序中没有窗口). 我还阅读了有关 ipc (例如命名管道)也需要HWND. 我想要这样的东西:

I have a windows console application which starts child process. How can I send a message to child process? I found functions like PostMessage()/PeekMessage() - that's what I need, but as I understand, it is used inside one application, and uses HWND to identify the target window (I have no windows in application). Also I've read materials about ipc, for example named pipes demand HWND too. I want something like that:

[program 1]

int main()
{
    CreateProcess(.., processInfo);
    SendMessage(processId, message);
}

[program 2]

int main()
{
    while(1)
    {
//      do thw work
        Sleep(5 * 1000);
//      check message
        if(PeekMessage(message,..))
        {
        break;
        }
    }
}

子进程需要获得消息,它应该完成其工作,而不是立即终止,而是要完成当前的迭代.这就是为什么我不使用信号并且阻止接收消息"也是不合适的原因.

Child process needs to get message that it should finish its work, not terminate immediately, but finish current iteration. That's why I don't use signals and blocking 'receive message' is not appropriate too.

[program 1]
int main()
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    std::string path = "c:\\program2.exe";
    CreateProcess(path.c_str(), .. , &si, &pi ) ) 
    Sleep(12 * 1000); // let program2 do some work
    PostThreadMessage(pi.dwThreadId, 100, 0, 0);
}

[program 2]
int main(int argc, char * argv[])
{
    MSG message;
    for(int i = 0; i < 1000; i++)
    {
        std::cout << "working" << std::endl;
        Sleep(2 * 1000);
        if(PeekMessage(&message, NULL, 0, 0, PM_NOREMOVE))
        {
            break;
        }
    }
}