Про cygwin и девайсы FIFO/SOCKET

Тема в разделе "WASM.BEGINNERS", создана пользователем device, 12 дек 2007.

  1. device

    device Reflection

    Публикаций:
    0
    Регистрация:
    26 апр 2007
    Сообщения:
    1.198
    Адрес:
    RF
    Тупой вопрос:
    Я переношу прогу из линуха на винду (cygwin).

    Прога в линуксе общается с устройствами:
    /dev/netlock и /dev/fxchannel
    Эти устройства она сама создает.

    В винде она нормально компилируется, а вот с запуском проблема. Что-то про права ругается...

    ВОПРОС :как в винде программировать устройства типа СОКЕТ и ТРУБА?
     
  2. LazzY

    LazzY New Member

    Публикаций:
    0
    Регистрация:
    6 мар 2006
    Сообщения:
    123
    =)
    рип про пайпы из мсднки, про сокеты тоже тамже можно найти
    Код (Text):
    1. #include <windows.h>
    2. #include <stdio.h>
    3.  
    4. #define BUFSIZE 4096
    5.  
    6. VOID InstanceThread(LPVOID);
    7. VOID GetAnswerToRequest(LPTSTR, LPTSTR, LPDWORD);
    8.  
    9. DWORD main(VOID)
    10. {
    11.    BOOL fConnected;
    12.    DWORD dwThreadId;
    13.    HANDLE hPipe, hThread;
    14.    LPTSTR lpszPipename = "\\\\.\\pipe\\mynamedpipe";
    15.  
    16. // The main loop creates an instance of the named pipe and
    17. // then waits for a client to connect to it. When the client
    18. // connects, a thread is created to handle communications
    19. // with that client, and the loop is repeated.
    20.  
    21.    for (;;)
    22.    {
    23.       hPipe = CreateNamedPipe(
    24.           lpszPipename,             // pipe name
    25.           PIPE_ACCESS_DUPLEX,       // read/write access
    26.           PIPE_TYPE_MESSAGE |       // message type pipe
    27.           PIPE_READMODE_MESSAGE |   // message-read mode
    28.           PIPE_WAIT,                // blocking mode
    29.           PIPE_UNLIMITED_INSTANCES, // max. instances  
    30.           BUFSIZE,                  // output buffer size
    31.           BUFSIZE,                  // input buffer size
    32.           NMPWAIT_USE_DEFAULT_WAIT, // client time-out
    33.           NULL);                    // no security attribute
    34.  
    35.       if (hPipe == INVALID_HANDLE_VALUE)
    36.       {
    37.           printf("CreatePipe failed");
    38.           return 0;
    39.       }
    40.  
    41.       // Wait for the client to connect; if it succeeds,
    42.       // the function returns a nonzero value. If the function returns
    43.       // zero, GetLastError returns ERROR_PIPE_CONNECTED.
    44.  
    45.       fConnected = ConnectNamedPipe(hPipe, NULL) ?
    46.          TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
    47.  
    48.       if (fConnected)
    49.       {
    50.       // Create a thread for this client.
    51.          hThread = CreateThread(
    52.             NULL,              // no security attribute
    53.             0,                 // default stack size
    54.             (LPTHREAD_START_ROUTINE) InstanceThread,
    55.             (LPVOID) hPipe,    // thread parameter
    56.             0,                 // not suspended
    57.             &dwThreadId);      // returns thread ID
    58.  
    59.          if (hThread == NULL)
    60.          {
    61.             printf("CreateThread failed");
    62.             return 0;
    63.          }
    64.          else CloseHandle(hThread);
    65.        }
    66.       else
    67.         // The client could not connect, so close the pipe.
    68.          CloseHandle(hPipe);
    69.    }
    70.    return 1;
    71. }
    72.  
    73. VOID InstanceThread(LPVOID lpvParam)
    74. {
    75.    CHAR chRequest[BUFSIZE];
    76.    CHAR chReply[BUFSIZE];
    77.    DWORD cbBytesRead, cbReplyBytes, cbWritten;
    78.    BOOL fSuccess;
    79.    HANDLE hPipe;
    80.  
    81. // The thread's parameter is a handle to a pipe instance.
    82.  
    83.    hPipe = (HANDLE) lpvParam;
    84.  
    85.    while (1)
    86.    {
    87.    // Read client requests from the pipe.
    88.       fSuccess = ReadFile(
    89.          hPipe,        // handle to pipe
    90.          chRequest,    // buffer to receive data
    91.          BUFSIZE,      // size of buffer
    92.          &cbBytesRead, // number of bytes read
    93.          NULL);        // not overlapped I/O
    94.  
    95.       if (! fSuccess || cbBytesRead == 0)
    96.          break;
    97.       GetAnswerToRequest(chRequest, chReply, &cbReplyBytes);
    98.  
    99.    // Write the reply to the pipe.
    100.       fSuccess = WriteFile(
    101.          hPipe,        // handle to pipe
    102.          chReply,      // buffer to write from
    103.          cbReplyBytes, // number of bytes to write
    104.          &cbWritten,   // number of bytes written
    105.          NULL);        // not overlapped I/O
    106.  
    107.       if (! fSuccess || cbReplyBytes != cbWritten) break;
    108.   }
    109.  
    110. // Flush the pipe to allow the client to read the pipe's contents
    111. // before disconnecting. Then disconnect the pipe, and close the
    112. // handle to this pipe instance.
    113.  
    114.    FlushFileBuffers(hPipe);
    115.    DisconnectNamedPipe(hPipe);
    116.    CloseHandle(hPipe);
    117. }
    118.  
    119. VOID GetAnswerToRequest(LPTSTR chRequest,
    120.    LPTSTR chReply, LPDWORD pchBytes)
    121. {
    122.    printf( "%s\n", chRequest );
    123.    lstrcpy( chReply, "default answer from server" );
    124.    *pcbBytes = lstrlen(chReply);
    125. }
     
  3. device

    device Reflection

    Публикаций:
    0
    Регистрация:
    26 апр 2007
    Сообщения:
    1.198
    Адрес:
    RF
    lapslap
    Спасибо. Про МСДН забыл... щас буду копать.

    P.S.: Если проштудировать этот код, можно вместо тредов - форкать. Тогда более понятнее станет:)
     
  4. device

    device Reflection

    Публикаций:
    0
    Регистрация:
    26 апр 2007
    Сообщения:
    1.198
    Адрес:
    RF
    What is it???
     
  5. censored

    censored New Member

    Публикаций:
    0
    Регистрация:
    5 июл 2005
    Сообщения:
    1.615
    Адрес:
    деревня "Анонимные Прокси"
    Имя пайпа
     
  6. device

    device Reflection

    Публикаций:
    0
    Регистрация:
    26 апр 2007
    Сообщения:
    1.198
    Адрес:
    RF
    Нарыл инфу... читаю.

    А вот интересно, если я захочу драйвер сетевого устройства написать, то в windows на си ведь его не напишешь - это не UNIX....
    Есть ли более понятная документация по работе с ядром Win32 (только не MSDN)?
    Я в винде начинающий - для меня пока это сложно. С драйвером в Unix - все нормально (есть куча примеров на си и фпсме), а вот c win32-проблема.

    censored

    Это какой-то особый вид URI?
     
  7. device

    device Reflection

    Публикаций:
    0
    Регистрация:
    26 апр 2007
    Сообщения:
    1.198
    Адрес:
    RF
    Интересно, есть ли фундаментальные алгоритмы для работы с трубами, сокетами, блоками и char девайсами? Ну то есть чтоб это работало не зависимо от системы операционной. Типа написал устройство один раз а запустил в любой ОС.