<?xml version='1.0' encoding="utf-8"?>
      <rss version='2.0'>
      <channel>
      <title>Форум на Исходниках.RU</title>
      <link>https://forum.sources.ru</link>
      <description>Форум на Исходниках.RU</description>
      <generator>Форум на Исходниках.RU</generator>
  	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=271568&amp;view=findpost&amp;p=2256881</guid>
        <pubDate>Mon, 04 May 2009 05:00:31 +0000</pubDate>
        <title>WaitForMultipleObjects, SOCKET, stdin</title>
        <link>https://forum.sources.ru/index.php?showtopic=271568&amp;view=findpost&amp;p=2256881</link>
        <description><![CDATA[leo: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=271568&view=findpost&p=2256713'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>Northsoft &#064; <time class="tag-quote__quoted-time" datetime="2009-05-03T21:49:47+04:00">03.05.09, 17:49</time></span><div class='quote '>Туда же, на &quot;соседнюю полочку&quot;, кладу дескриптор _fileno(stdin).<br>
Причем если не добавлять _fileno(stdin), то всё работает прекрасно</div></div><br>
Ес-но, т.к. это не виндовый дескриптор, а crt-шный = указателю на структуру FILE.<br>
Используй GetStdHandle]]></description>
        <author>leo</author>
        <category>C/C++: Сетевое программирование</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=271568&amp;view=findpost&amp;p=2256781</guid>
        <pubDate>Sun, 03 May 2009 20:29:00 +0000</pubDate>
        <title>WaitForMultipleObjects, SOCKET, stdin</title>
        <link>https://forum.sources.ru/index.php?showtopic=271568&amp;view=findpost&amp;p=2256781</link>
        <description><![CDATA[progman: <div class='tag-quote'><a class='tag-quote-link' href='https://forum.sources.ru/index.php?showtopic=271568&view=findpost&p=2256713'><span class='tag-quote-prefix'>Цитата</span></a> <span class='tag-quote__quote-info'>Northsoft &#064; <time class="tag-quote__quoted-time" datetime="2009-05-03T17:49:47+00:00">03.05.09, 17:49</time></span><div class='quote '>Туда же, на &quot;соседнюю полочку&quot;, кладу дескриптор _fileno(stdin).<br>
<br>
WaitForMultipleObjects при этом возвращает WAIT_FAILED, GetLastError возвращает ERROR_INVALID_HANDLE. Причем если не добавлять _fileno(stdin), то всё работает прекрасно, однако с не меньшим успехом я мог бы воспользоваться и уже привычным мне select.</div></div><br>
<div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <div class='quote '>The WaitForMultipleObjects function can specify handles of any of the following object types in the lpHandles array: <br>
<br>
Change notification <br>
Console input <br>
Event <br>
Job <br>
Mutex <br>
Process <br>
Semaphore <br>
Thread <br>
Waitable timer <br>
<br>
<br>
Though available for other uses, the following objects can also be used for synchronization. <br>
<br>
<strong class='tag-b'>Change notification</strong> Created by the FindFirstChangeNotification function, its state is set to signaled when a specified type of change occurs within a specified directory or directory tree. For more information, see File I/O. <br>
 <br>
<strong class='tag-b'>Console input</strong> Created when a console is created. The handle to console input is returned by the CreateFile function when CONIN&#036; is specified, or by the GetStdHandle function. Its state is set to signaled when there is unread input in the console&#39;s input buffer, and set to nonsignaled when the input buffer is empty. For more information about consoles, see Consoles and Character-Mode Support.  <br>
<br>
<strong class='tag-b'>Job</strong> Created by calling the CreateJobObject function. The state of a job object is set to signaled when all its processes are terminated because the specified end-of-job time limit has been exceeded. For more information about job objects, see Job Objects.  <br>
<br>
<strong class='tag-b'>Process</strong> Created by calling the CreateProcess function. Its state is set to nonsignaled while the process is running, and set to signaled when the process terminates. For more information about processes, see Processes and Threads.  <br>
<br>
<strong class='tag-b'>Thread</strong> Created when a new thread is created by calling the CreateProcess, CreateThread, or CreateRemoteThread function. Its state is set to nonsignaled while the thread is running, and set to signaled when the thread terminates. For more information about threads, see Processes and Threads.  <br>
</div></div> <br>
<br>
<span class="tag-color tag-color-named" data-value="gray" style="color: gray"><span class='tag-size' data-value='7' style='font-size:7pt;'>Добавлено <time class="tag-mergetime" datetime="2009-05-03T20:30:24+00:00">03.05.09, 20:30</time></span></span><br>
короче, если я правильно понимаю и не туплю, то юзай WinAPI и будет тебе счастие а разбавлять WinAPI ( WSAEventSelect ) и CRT (_fileno(stdin)) имхо не верно.]]></description>
        <author>progman</author>
        <category>C/C++: Сетевое программирование</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=271568&amp;view=findpost&amp;p=2256713</guid>
        <pubDate>Sun, 03 May 2009 17:49:47 +0000</pubDate>
        <title>WaitForMultipleObjects, SOCKET, stdin</title>
        <link>https://forum.sources.ru/index.php?showtopic=271568&amp;view=findpost&amp;p=2256713</link>
        <description><![CDATA[Northsoft: Требуется мультиплексирование серверного сокета и стандартного потока ввода:<br>
Сервер-демон запускается, прислушивается к порту. Если приходит входящее соединение, то сервер для него создает поток и дальнейшая работа производится уже вне основного потока.<br>
Если получен ввод на консоль - завершить работу.<br>
Все действия должны предприниматься <span class='tag-u'>незамедлительно</span>. Поэтому требуется мультиплексирование как сетевого сокета, так и стандартного потока ввода.<br>
В UNIX для этого обычно используется <a class='tag-url' href='http://www.opennet.ru/man.shtml?topic=select&category=2&russian=0' target='_blank'>select</a>. Однако в Windows функция <a class='tag-url' href='http://msdn.microsoft.com/en-us/library/ms740141(VS.85).aspx' target='_blank'>select</a> входит в состав библиотеки WinSock 2 и поддерживает мультиплексирование исключительно сетевых сокетов. После активного использования Google я нашел функцию <a class='tag-url' href='http://msdn.microsoft.com/en-us/library/ms687025(VS.85).aspx' target='_blank'>WaitForMultipleObjects</a>, которая поддерживает мультиплексирование консольного ввода вывода и событий. С помощью функции <a class='tag-url' href='http://msdn.microsoft.com/en-us/library/ms741576(VS.85).aspx' target='_blank'>WSAEventSelect</a> я создаю дескриптор, совместимый с событийным мультиплексором и сохраняю его в массив типа HANDLE[]. Туда же, на &quot;соседнюю полочку&quot;, кладу дескриптор <a class='tag-url' href='http://msdn.microsoft.com/en-us/library/zs6wbdhx(VS.80).aspx' target='_blank'>_fileno</a>(stdin).<br>
<br>
<a class='tag-url' href='http://msdn.microsoft.com/en-us/library/ms687025(VS.85).aspx' target='_blank'>WaitForMultipleObjects</a> при этом возвращает WAIT_FAILED, <a class='tag-url' href='http://msdn.microsoft.com/en-us/library/ms679360(VS.85).aspx' target='_blank'>GetLastError</a> возвращает ERROR_INVALID_HANDLE. Причем если не добавлять <a class='tag-url' href='http://msdn.microsoft.com/en-us/library/zs6wbdhx(VS.80).aspx' target='_blank'>_fileno</a>(stdin), то всё работает прекрасно, однако с не меньшим успехом я мог бы воспользоваться и уже привычным мне <a class='tag-url' href='http://msdn.microsoft.com/en-us/library/ms740141(VS.85).aspx' target='_blank'>select</a>. <br>
<br>
Ну и код напоследок.<br>
<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">#include &#60;stdio.h&#62;</div><div class="code_line">#include &#60;stdlib.h&#62;</div><div class="code_line">#include &#60;winsock2.h&#62;</div><div class="code_line">&nbsp;</div><div class="code_line">int main(int argc, char *argv[], char **env){</div><div class="code_line">&nbsp;&nbsp; &nbsp;char *ip;</div><div class="code_line">&nbsp;&nbsp; &nbsp;DWORD wfmret;</div><div class="code_line">&nbsp;&nbsp; &nbsp;int cycle_accept; </div><div class="code_line">&nbsp;&nbsp; &nbsp;int port;</div><div class="code_line">&nbsp;&nbsp; &nbsp;HANDLE eventHandle;</div><div class="code_line">&nbsp;&nbsp; &nbsp;HANDLE wfm[2];</div><div class="code_line">&nbsp;&nbsp; &nbsp;SOCKET *s;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WSADATA wsaData;</div><div class="code_line">&nbsp;&nbsp; &nbsp;struct sockaddr_in service;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;cycle_accept=0;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;ip=malloc(sizeof(char)*10);</div><div class="code_line">&nbsp;&nbsp; &nbsp;memset(ip,0,10);</div><div class="code_line">&nbsp;&nbsp; &nbsp;strncpy_s(ip,10,&quot;127.0.0.1&quot;,10);</div><div class="code_line">&nbsp;&nbsp; &nbsp;port=91462;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;WSAStartup(MAKEWORD(2,2),&amp;wsaData);</div><div class="code_line">&nbsp;&nbsp; &nbsp;s=malloc(sizeof(SOCKET));</div><div class="code_line">&nbsp;&nbsp; &nbsp;*s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);</div><div class="code_line">&nbsp;&nbsp; &nbsp;service.sin_family=AF_INET;</div><div class="code_line">&nbsp;&nbsp; &nbsp;service.sin_addr.s_addr=inet_addr(ip);</div><div class="code_line">&nbsp;&nbsp; &nbsp;service.sin_port=htons(port);</div><div class="code_line">&nbsp;&nbsp; &nbsp;bind(*s,(SOCKADDR *)&amp;service,sizeof(service));</div><div class="code_line">&nbsp;&nbsp; &nbsp;listen(*s,1);</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp;cycle_accept=1;</div><div class="code_line">&nbsp;&nbsp; &nbsp;while(cycle_accept==1){</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;eventHandle=WSACreateEvent();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;WSAEventSelect(*s,eventHandle,FD_ACCEPT);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;wfm[0]=eventHandle;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;wfm[1]=_fileno(stdin);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;wfmret=WaitForMultipleObjects(2,wfm,FALSE,5000);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;WSACloseEvent(eventHandle);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;if(wfmret==-1){</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;printf(&quot;Error code %d\n&quot;,GetLastError());</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;getchar();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;cycle_accept=0;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp;shutdown(*s,SD_BOTH);</div><div class="code_line">&nbsp;&nbsp; &nbsp;closesocket(*s);</div><div class="code_line">&nbsp;&nbsp; &nbsp;free(ip);</div><div class="code_line">&nbsp;&nbsp; &nbsp;free(s);</div><div class="code_line">&nbsp;&nbsp; &nbsp;return 0;</div><div class="code_line">}</div></ol></div></div></div></div><script>preloadCodeButtons('1');</script>]]></description>
        <author>Northsoft</author>
        <category>C/C++: Сетевое программирование</category>
      </item>
	
      </channel>
      </rss>
	