简体   繁体   中英

named pipe windows behaves

I'm trying to create a basic server with a named pipe in windows. The problem occurs when trying to connect the pipes(I suspect).

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

int main(){
    HANDLE p1, p2;
    printf("Server...");
    p1 = CreateNamedPipe(TEXT("\\\\.\\PIPE\\pipe1"),PIPE_ACCESS_INBOUND,PIPE_TYPE_BYTE|PIPE_WAIT,3,0,0,0,NULL);
    p2 = CreateNamedPipe(TEXT("\\\\.\\PIPE\\pipe2"),PIPE_ACCESS_OUTBOUND,PIPE_TYPE_BYTE|PIPE_WAIT,3,0,0,0,NULL);
    if(p1 == INVALID_HANDLE_VALUE || p2 ==  INVALID_HANDLE_VALUE ) { printf("pipe fail");exit(2);}
    printf("1. Pipes created");
    ConnectNamedPipe(p1,NULL);
    ConnectNamedPipe(p2,NULL);
    printf("2. Pipes connected");


    DisconnectNamedPipe(p1);
    DisconnectNamedPipe(p2);
    CloseHandle(p1);
    CloseHandle(p2);
    printf("3. Pipes disconnected & closed");

    printf("exit server...");

    return 0;

}

When running the program, it doesn't print anything and when i manually stop it it just prints Server...1. Pipes created Server...1. Pipes created (in my IDE console - Eclipse) or if I run program directly it, it prints the same then it holds.

It takes two to tango here. You'll need to write another program that calls CreateFile() to open the named pipe. Only then will the ConnectNamedPipe() call in your server program complete. Avoid using two pipes in your test program, pipes are bi-directional so you only need a single pipe to talk back-and-forth. If you want to support multiple clients then simply call ConnectNamedPipe again after a pipe connection was established. At which point it also becomes important to use overlapped I/O or threads.

Do take a look at the sample code included in the MSDN articles for named pipes. It shows you how to write both the server and client code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM