本文介绍了是否有可靠地使用write()函数一个更清洁的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读页,我的理解是,如果的write()将失败,并将在错误号 EAGAIN EINTR ,我可以执行的write()了,所以我想出了以下code:

I read the man pages, and my understanding is that if write() fails and sets the errno to EAGAIN or EINTR, I may perform the write() again, so I came up with the following code:

  ret = 0;
  while(ret != count) {
    write_count = write(connFD, (char *)buf + ret,  count);
    while (write_count < 0) {
      switch(errno) {
        case EINTR:
        case EAGAIN:
          write_count = write(connFD, (char *)buf + ret,  count -ret);
          break;
        default:
          printf("\n The value of ret is : %d\n", ret);
          printf("\n The error number is : %d\n", errno);      
          ASSERT(0);
      }
    }
    ret += write_count;
  }

我执行阅读()的write()上的插座和处理阅读()类似如上。我使用Linux,以 GCC 编译器。

I am performing read() and write() on sockets and handling the read() similarly as above. I am using Linux, with gcc compiler.

推荐答案

您有一个有点不重复自己的问题存在 - 没有必要为两个单独的呼叫到,也有两个嵌套循环。

You have a bit of a "don't repeat yourself" problem there - there's no need for two separate calls to write, nor for two nested loops.

我的正常循环就会是这个样子:

My normal loop would look something like this:

for (int n = 0; n < count; ) {
    int ret = write(fd, (char *)buf + n, count - n);
    if (ret < 0) {
         if (errno == EINTR || errno == EAGAIN) continue; // try again
         perror("write");
         break;
    } else {
        n += ret;
    }
}

// if (n < count) here some error occurred

这篇关于是否有可靠地使用write()函数一个更清洁的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 11:54