Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send a message from one windows console application to another?

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.

like image 843
diana-pure Avatar asked Oct 02 '22 10:10

diana-pure


1 Answers

[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;
        }
    }
}
like image 74
diana-pure Avatar answered Oct 13 '22 10:10

diana-pure