На главную

On-line справка по Win32 API

Написать письмо
БЕСПЛАТНАЯ ежедневная online лотерея! Выигрывай каждый день БЕСПЛАТНО!
Список всех статей A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z | Скачать Вниз

ConnectNamedPipe



The ConnectNamedPipe function enables a named pipe server process to wait for a client process to connect to an instance of a named pipe. A client process connects by calling either the CreateFile or CallNamedPipe function.

BOOL ConnectNamedPipe(

HANDLE hNamedPipe, // handle to named pipe to connect
LPOVERLAPPED lpOverlapped // pointer to overlapped structure
);


Parameters

hNamedPipe

Identifies the server end of a named pipe instance. This handle is returned by the CreateNamedPipe function.

lpOverlapped

Points to an OVERLAPPED structure.



Return Values

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

A named pipe server process can use ConnectNamedPipe with a newly created pipe instance. It can also be used with an instance that was previously connected to another client process; in this case, the server process must first call the DisconnectNamedPipe function to disconnect the handle from the previous client before the handle can be reconnected to a new client. Otherwise, ConnectNamedPipe returns FALSE, and GetLastError returns ERROR_NO_DATA if the previous client has closed its handle or ERROR_PIPE_CONNECTED if it has not closed its handle.

The behavior of ConnectNamedPipe depends on two conditions: whether the pipe handle's wait mode is set to blocking or nonblocking and whether the function is set to execute synchronously or in overlapped mode. A server initially specifies a pipe handle's wait mode in the CreateNamedPipe function, and it can be changed by using the SetNamedPipeHandleState function.
If hNamedPipe was opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must not be NULL. It must point to a valid OVERLAPPED structure. If hNamedPipe was opened with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the function can incorrectly report that the connect operation is complete.

If hNamedPipe was created with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the OVERLAPPED structure pointed to by lpOverlapped must contain a handle to a manual-reset event object (which the server can create by using the CreateEvent function).
If hNamedPipe was not opened with FILE_FLAG_OVERLAPPED and lpOverlapped is NULL, the function does not return until a client is connected or an error occurs. Successful synchronous operations result in the function returning TRUE if a client connects after the function is called. If a client connects before the function is called, the function returns FALSE and GetLastError returns ERROR_PIPE_CONNECTED. This can happen if a client connects in the interval between the call to CreateNamedPipe and the call to ConnectNamedPipe. In this situation, there is a good connection between client and server, even though the function returns FALSE.

If hNamedPipe was not opened with FILE_FLAG_OVERLAPPED and lpOverlapped is not NULL, the operation executes asynchronously. The function returns immediately with a return value of FALSE. If a client process connects before the function is called, GetLastError returns ERROR_PIPE_CONNECTED. Otherwise, GetLastError returns ERROR_IO_PENDING, which indicates that the operation is executing in the background. When this happens, the event object in the OVERLAPPED structure is set to the nonsignaled state before ConnectNamedPipe returns, and it is set to the signaled state when a client connects to this instance of the pipe.

The server process can use any of the wait functions or SleepEx ѕ to determine when the state of the event object is signaled, and it can then use the GetOverlappedResult function to determine the results of the ConnectNamedPipe operation.
If the specified pipe handle is in nonblocking mode, ConnectNamedPipe always returns immediately. In nonblocking mode, ConnectNamedPipe returns TRUE the first time it is called for a pipe instance that is disconnected from a previous client. This indicates that the pipe is now available to be connected to a new client process. In all other situations when the pipe handle is in nonblocking mode, ConnectNamedPipe returns FALSE. In these situations, GetLastError returns ERROR_PIPE_LISTENING if no client is connected, ERROR_PIPE_CONNECTED if a client is connected, and ERROR_NO_DATA if a previous client has closed its pipe handle but the server has not disconnected. Note that a good connection between client and server exists only after the ERROR_PIPE_CONNECTED error is received.

Note that nonblocking mode is supported for compatibility with Microsoft LAN Manager version 2.0, and it should not be used to achieve asynchronous input and output (I/O) with named pipes.

See Also

CallNamedPipe, CreateEvent, CreateFile, CreateNamedPipe, DisconnectNamedPipe, GetOverlappedResult, SetNamedPipeHandleState, SleepEx, OVERLAPPED


Пригласи друзей и счет твоего мобильника всегда будет положительным!
Предыдущая статья
 
Сайт Народ.Ру Интернет
Следующая статья
Пригласи друзей и счет твоего мобильника всегда будет положительным!

ConnectNamedPipe



Функция ConnectNamedPipe позволяет процесс сервера поименованной трубы, чтобы ждать процесс клиента, чтобы подключать к примеру поименованной трубы. Процесс клиента соединяется вызывая или CreateFile или функция CallNamedPipe.

BOOL ConnectNamedPipe(

РУЧКА hNamedPipe, // оперируется на назвавшее трубу, чтобы соединять LPOVERLAPPED lpOverlapped // указатель на перекрывшее структуру
);


Параметры

hNamedPipe

Идентифицирует конец сервера поименованного примера трубы. Эта ручка возвращана функцией CreateNamedPipe.

lpOverlapped

Точки на ПЕРЕКРЫТУЮ структуру.



Обратные Величины

Если функция добивается успеха, обратная величина ненулевая.
Если функция терпит неудачу, обратная величина нулевая. Для того, чтобы расширять информацию ошибки, назовите GetLastError.

Замечания

Процесс сервера поименованной трубы может использовать ConnectNamedPipe с вновь созданным примером трубы. Это может также использовано примером, который прежде был подключен к другому процессу клиента; в этом случае, процесс сервера должен сначала назвать функцию DisconnectNamedPipe, чтобы отключать ручку от предшествующего клиента прежде, чем ручка может быть пересоединена новому клиенту. В противном случае, ЛОЖЬ возврата ConnectNamedPipe, и возврат GetLastError ERROR_NO_DATA если предшествующий клиент закрыл бы свою ручку или ERROR_PIPE_CONNECTED если он не закрыл бы свою ручку.

Поведение ConnectNamedPipe зависит от двух условий: установлен режим ожидания ручки трубы в блокировку или nonblocking и установлена функция, чтобы выполнять синхронно или в перекрытом режиме. Сервер первоначально определяет режим ожидания ручки трубы в функции CreateNamedPipe, и может быть изменено использованием функции SetNamedPipeHandleState.
Если hNamedPipe был открыт FILE_FLAG_OVERLAPPED, lpOverlapped параметр не должен быть НЕДЕЙСТВИТЕЛЕН. Это должно указать на правильную ПЕРЕКРЫТУЮ структуру. Если hNamedPipe был открыт FILE_FLAG_OVERLAPPED и lpOverlapped НЕДЕЙСТВИТЕЛЕН, функция может неправильно сообщить, что соединять операцию завершенно.

Если hNamedPipe был создан FILE_FLAG_OVERLAPPED и lpOverlapped не НЕДЕЙСТВИТЕЛЕН, ПЕРЕКРЫТАЯ структура указанная, чтобы lpOverlapped должна содержать ручку в руководство-восстановившее объект события (который сервер может создать используя функцию CreateEvent).
Если hNamedPipe не был открыт FILE_FLAG_OVERLAPPED и lpOverlapped НЕДЕЙСТВИТЕЛЕН, функция не возвращается пока клиент не будет связан или ошибка происходит. Успешные синхронные операции заканчиваются функцией, возвращать ИСТИНУ если клиент соединяется после того, как функция будет названа. Если клиент соединяется прежде, чем функция будет названа, функция возвращает ЛОЖЬ и возврат GetLastError ERROR_PIPE_CONNECTED. Это может случиться если клиент соединяется в интервал между вызовом на CreateNamedPipe и вызов на ConnectNamedPipe. В этой ситуации, есть хорошая связь между клиентом и сервером, даже если функция возвращает ЛОЖЬ.

Если hNamedPipe не был открыт FILE_FLAG_OVERLAPPED и lpOverlapped не НЕДЕЙСТВИТЕЛЕН, операция выполняется асинхронно. Функция возвращается немедленно с обратной величиной ЛЖИ. Если процесс клиента соединяется прежде, чем функция будет названа, возврат GetLastError ERROR_PIPE_CONNECTED. В противном случае, возврат GetLastError ERROR_IO_PENDING, который указывает, что операция выполняется на фоне. Когда это случается, объект события в ПЕРЕКРЫТОЙ структуре установлен в nonsignaled состояние перед возврат ConnectNamedPipe, и установлено в сигнальное состояние когда клиент подключает к этому примеру трубы.

Процесс сервера может использовать любую из функций ожидания или SleepEx U, чтобы определяться когда состояние объекта события сигнализировано, и это может затем использовать функцию GetOverlappedResult, чтобы определять результаты операции ConnectNamedPipe.
Если определенная ручка трубы - в nonblocking режиме, всегда возврате ConnectNamedPipe немедленно. В nonblocking режиме, ИСТИНА возврата ConnectNamedPipe сначала названо к примеру трубы, который разъединен от предшествующего клиента. Это указывает, что труба теперь доступна быть подключенн к новому процессу клиента. Во всех других ситуациях когда ручка трубы - в nonblocking режиме, ЛЖИ возврата ConnectNamedPipe. В этих ситуациях, возврате GetLastError ERROR_PIPE_LISTENING если никакой клиент не связан, ERROR_PIPE_CONNECTED если клиент связан, и ERROR_NO_DATA если предшествующий клиент закрыл бы свою ручку трубы но сервер не разъединился. Отметьте, что хорошая связь между клиентом и сервером существует только после того, как ошибка ERROR_PIPE_CONNECTED будет получена.

Отметьте, что nonblocking режима поддерживан для совместимости с версией Менеджера Микрософт LAN 2.0, и это не должно использовано, чтобы достигать асинхронного ввода и выхода (В/В) с поименованными трубами.

Смотри Также

CallNamedPipe, CreateEvent, CreateFile, CreateNamedPipe, DisconnectNamedPipe, GetOverlappedResult, SetNamedPipeHandleState, SleepEx, ПЕРЕКРЫТОЕ


Вверх Version 1.3, Oct 26 2010 © 2007, 2010, mrhx Вверх
 mrhx software  Русский перевод OpenGL  Русский перевод Win32 API
 
Используются технологии uCoz