1

POSIXCWindows(WinSocks 2.2)に移植しているコードがいくつかあり、(だけでなく)のMS実装に問題がありpoll()ます。

私は POSIX についてある程度の経験がありsocketsますが、WinSock2 についてはまったくの初心者です。MSDN で役立つ手がかりが見つからなかったので、ここで質問します。

static int connect_to_addr(char *address, char *port)
{
    struct addrinfo hints;
    struct addrinfo *addr;
    int fd;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = PF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_NUMERICHOST;

    if (getaddrinfo(address, port, &hints, &addr) != 0) return -1;

    fd = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
    if (fd < 0) return -1;

    if (connect(fd, addr->ai_addr, addr->ai_addrlen) < 0) return -1;

    freeaddrinfo(addr);
    return fd;
}

関数は、2 番目のフィールドがconnect_to_addr()どのように見えるかを示すためのものです。fd

WSAStartup(...)
...
pollfd cinfd[2];
fds[0].fd = _fileno(stdin); //THIS is probably not supported on win32 
fds[0].events = POLLIN;
fds[1].fd = f_connect(some_addr, some_port); //OK
fds[1].events = POLLIN;

while (1) {
    res = WSAPoll(fds, 2, -1); //returns 1

    if (fds[0].revents & (POLLIN | POLLHUP)) { //fds[0].revents == POLLNVAL  !! problem
        char buf[1024];
        int n, w, i;
        n = read(fds[0].fd, buf, 1024);
        ...
    }

    if (fds[1].revents & POLLIN) {
        char buf[1024];
        int n, w, i;
        n = recv(fds[1].fd, buf, 1024, 0);
        ...
    }
}

この一般的なイディオムを WinSocks で実装するにはどうすればよいですか? 提案をありがとう。

さらに良いことに、WSAPoll() は Vista 以降 ws2_32.dll にあります。XPで動作させるには?

4

1 に答える 1

0

stdin/sock の待機には WaitForMultipleObjects() を使用することをお勧めします。

HANDLE h[2];
h[0] = GetStdHandle(STD_INPUT_HANDLE);
h[1] = sock;

while (1) {
    DWORD ret;
    ret = WaitForMultipleObjects(2, h, FALSE, 0 /* wait value you want */);

    if (ret == WAIT_OBJECT_0) {
        // munipulating stdin.
    }
    if (ret == WAIT_OBJECT_0 + 1) {
        // munipulating sock.
        // then call recv.
    }
}
于 2011-06-21T06:04:43.517 に答える