qwn
qwn

Reputation: 367

Named Pipe communication between service and application

So I have a service which starts at boot time, and I have an application which I have placed in the startup folder.

So the client sometimes connects very late to the server of the named pipe.

Here is my code in my service.

hPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\popupPipe"),
                    PIPE_ACCESS_DUPLEX | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,   // FILE_FLAG_FIRST_PIPE_INSTANCE is not needed but forces CreateNamedPipe(..) to fail if the pipe already exists...
                    PIPE_WAIT,
                    1, 1024 * 16, 1024 * 16,
                    NMPWAIT_USE_DEFAULT_WAIT,
                    NULL);

HRESULT
SendMessage(){
    if (ConnectNamedPipe(hPipe, NULL) != FALSE) {   // wait for someone to connect to the pipe
        WriteFile(hPipe, (char *)message->buffer, sizeof(message->buffer), &dwWritten, NULL);
        return S_OK;
    }
    return E_FAIL;
}

and here is the application

hPipe = CreateFile(TEXT("\\\\.\\pipe\\popupPipe"),
                    GENERIC_READ | GENERIC_WRITE,
                    0,
                    NULL,
                    OPEN_EXISTING,
                    0,
                    NULL);

if (hPipe == INVALID_HANDLE_VALUE)
    return -1;

while (hPipe != INVALID_HANDLE_VALUE)
{
    DWORD dwRead;
    char buffer[100] = { 0 };
    while (ReadFile(hPipe, buffer, sizeof(buffer), &dwRead, NULL) != FALSE);
    if (dwRead == sizeof(buffer)) {
        dwRead = 0;
        buffer[100] = '\0';
        temp = &buffer[1];
        DisplayPopup(hInstance, cmdShow);
    }
}
return 0;

but at the clients end the application always returns INVALID_HANDLE_VALUE

In the service SendMessage is called multiple times so even if it fails the first times it should succeed when the client connects shouldn't it.

Upvotes: 1

Views: 1034

Answers (1)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

You don't check if the creation of the pipe suceeds. Looking at the Microsoft documentation, it probably does not succeed because you mix parameters:

hPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\popupPipe"),
                PIPE_ACCESS_DUPLEX | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,   // FILE_FLAG_FIRST_PIPE_INSTANCE is not needed but forces CreateNamedPipe(..) to fail if the pipe already exists...
                PIPE_WAIT,
                1, 1024 * 16, 1024 * 16,
                NMPWAIT_USE_DEFAULT_WAIT,
                NULL);

should be:

hPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\popupPipe"),
                PIPE_ACCESS_DUPLEX,              // FILE_FLAG_FIRST_PIPE_INSTANCE is not needed but forces CreateNamedPipe(..) to fail if the pipe already exists...
                PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
                1, 1024 * 16, 1024 * 16,
                NMPWAIT_USE_DEFAULT_WAIT,
                NULL);

Upvotes: 3

Related Questions