Connecting to an Existing Pipe

After a server opens a named pipe, it must wait for a client to open the other end. A client may open its end in any of several ways, but the most common is the CreateFile function. This is the same function you use to open disk files. It also works with named pipes, communications devices, and the I/O buffers of a character-based console window. The ReadFile and WriteFile commands also work with the same set of objects. Using a single unified API for several different objects makes programming easier.

HANDLE CreateFile(
   LPCTSTR lpszName,           // name of the pipe (or file)
   DWORD fdwAccess,            // read/write access (must match the pipe)
   DWORD fdwShareMode,         // usually 0 (no share) for pipes
   LPSECURITY_ATTRIBUTES lpsa, // access privileges
   DWORD fdwCreate,            // must be OPEN_EXISTING for pipes
   DWORD fdwAttrsAndFlags,     // write-through and overlapping modes
   HANDLE hTemplateFile );     // ignored with OPEN_EXISTING

The pipe name must match the string the server passed to CreateNamedPipe. If the server and client programs are connecting over a network, the string must name the network server machine instead of using a dot (.).

The fdwAccess parameter tells whether you want to read or write to the pipe. If the pipe was created with the PIPE_ACCESS_OUTBOUND flag, you should specify GENERIC_READ in CreateFile. For an inbound pipe, the client needs GENERIC_WRITE privileges. For a duplex pipe, the client needs GENERIC_READ | GENERIC_WRITE privileges.

The fdwShareMode should generally be 0 to prohibit sharing the pipe with other processes. Occasionally, however, a client might use the share mode to duplicate the pipe handle for another client. In that case, both clients have handles to the same instance of the same pipe, and you  might need to worry about synchronizing their read and write operations.

The security attributes in the lpsa parameter should be familiar to you by now. The fdwCreate flag must be set to OPEN_EXISTING because CreateFile will not create a new pipe; it simply opens existing pipes. Other flags allow CreateFile to create new file objects where none existed before, but those flags produce errors when lpszName designates a pipe object.

The last two parameters normally govern file attributes, such as hidden, read-only, and archive settings, but CreateFile uses the attributes only to create new files. When you open an existing object (with OPEN_EXIST), the object keeps whatever attributes it already has. However, there are two exceptions; two flags in the fdwAttrsAndFlags parameters do work when opening an existing named pipe: FILE_FLAG_WRITE_THROUGH and FILE_FLAG_OVERLAPPED. The client may set flags that differ from the server, enabling or disabling network buffering and asynchronous I/O to suit its own preferences.

© 1998 SYBEX Inc. All rights reserved.