/* C program that reads and writes a Windows NT named pipe */
/* 1. Declare include files */ #include <windows.h> #include <stdio.h> #include <wincon.h> #include <winerror.h> #include <conio.h> void main() { /* 2. Define automatic data items */ HANDLE hPipe; char buffer[4096]; DWORD dwBytesRead; BOOL bRet; int iPipeType; int iLen; /* 3. Make window title meaningful */ /* 4. Create the named pipe */ printf("Creating Named Pipe custpipe\n"); hPipe = CreateNamedPipe("\\\\.\\pipe\\custpipe", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 0, 0, NMPWAIT_USE_DEFAULT_WAIT, NULL); if (hPipe == INVALID_HANDLE_VALUE) { printf("Error creating pipe, %ld\n", GetLastError()); exit(GetLastError()); } printf("custpipe created successfully\n"); /* 5. Solicit user input */ do { printf("\nPress 1 for Read, 2 for Write: "); iPipeType = getch(); } while (iPipeType != '1' && iPipeType != '2'); /* 6. Connect the named pipe */ printf("\nWaiting for connection..."); if (ConnectNamedPipe(hPipe, NULL) == FALSE) { printf("Error connecting to named pipe, %ld", GetLastError()); exit(GetLastError()); } printf("and connection established\n"); |
/* 7. Read and write the pipe */
switch(iPipeType) { case '1': /* read */ while (TRUE) { bRet = ReadFile(hPipe, &buffer, 4096, &dwBytesRead, NULL); if (bRet == FALSE) { /* if the pipe went away, the ABL app did an OUTPUT CLOSE */ if (GetLastError() == ERROR_BROKEN_PIPE) printf("Error reading from pipe, %ld\n", GetLastError()); break; } printf("Data read = %ld %s\n", dwBytesRead, buffer); } /* end while */ break; /*} end switch */ case '2': /* write */ while (TRUE) { printf( "Enter data to send, followed by ENTER: (Blank to exit) \n" ); gets(buffer); if (buffer[0] == 0) break; iLen = strlen(buffer); buffer[iLen++] = 0x0d; /* CR */ buffer[iLen++] = 0x0a; /* LF */ bRet = WriteFile(hPipe, &buffer, (DWORD) iLen, &dwBytesRead, NULL); if (bRet) { FlushFileBuffers(hPipe); printf("%ld bytes flushed to pipe\n", dwBytesRead); } else printf("Error writing to pipe: %d\n", GetLastError()); } /* end while */ break; } /* end switch */ /* 8. Close and exit */ CloseHandle(hPipe); printf("custpipe closed successfully\nBye"); } |