5

我正在一个套接字上进行一个非阻塞发送调用,然后在另一个套接字上进行阻塞接收。之后我想检查非阻塞发送是成功还是失败。如何才能做到这一点?

    while (i)
    {
      retval = send (out_sd, s_message, strlen (s_message), MSG_DONTWAIT);
      retval = recv (client_sd, r_message, MSG_LEN, 0);
      r_message[retval] = '\0';
      /* Here I want to wait for the non-blocking send to complete */
      strcpy (s_message, r_message);
      strcpy (r_message, "");
      i--;
    }
4

2 回答 2

5

您以某种方式混合了同步和异步 IO,这通常有点令人困惑,但我在这里看不到任何实际问题。

为避免硬轮询(不断查看您的操作是否已在循环中完成),您应该使用 select() 等待您的通道/套接字可用于更多写入操作。这将告诉您前一个已完成(或者它已完全由您的操作系统负责,这是相同的)。

select() 函数是 C 中异步 IO 的基础,您应该在此处阅读它,是一个我认为可能对您有用的示例。

请注意,尽管 select() 支持读取、写入和异常事件,示例显示了读取选择,您想要执行写入选择。

于 2012-12-12T14:49:32.183 回答
1

send() will return you the number of bytes sent or -1 in case of an error.

If there's enough buffer in the network stack to send at least some bytes from your message, retval will contain the number of bytes sent, which may be less than the number of bytes you wanted to send. If the network stack buffer is full, it will contain -1 and errno will be set to EAGAIN or EWOULDBLOCK.

In all cases, the send call is complete as soon as it returns. So you do not have to wait for the non-blocking send to complete anywhere else, you need to check the return value right away after the send() call returns.

于 2012-12-12T14:55:04.010 回答