OS X 上的 AIO 与 Linux - 为什么它在 Mac OS X 10.6 上不起作用

inv*_*ode 5 c++ aio aio-write

我的问题很简单。为什么下面的代码可以在 Linux 上运行,但不能在 Mac OS X 10.6.2 Snow Leopard 上运行。

要编译,请将文件保存到 aio.cc,并g++ aio.cc -o aio -lrt在 Linux 和g++ aio.cc -o aioMac OS X 上进行编译。我使用 Mac OS X 10.6.2 在 Mac 上进行测试,并使用 Linux 内核 2.6 在 Linux 上进行测试。

我在 OS X 上看到的故障是 aio_write 失败,返回 -1 并将 errno 设置为 EAGAIN,这只是意味着“资源暂时不可用”。这是为什么?

extern "C" {
#include <aio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include <signal.h>
}
#include <cassert>
#include <string>
#include <iostream>

using namespace std;

static void
aio_completion_handler(int signo, siginfo_t *info, void *context)
{
  using namespace std;
  cout << "BLAH" << endl;
}


int main()
{
  int err;

  struct sockaddr_in sin;
  memset(&sin, 0, sizeof(sin));

  sin.sin_port = htons(1234);
  sin.sin_addr.s_addr = inet_addr("127.0.0.1");
  sin.sin_family = PF_INET;

  int sd = ::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (sd == -1) {
    assert(!"socket() failed");
  }

  const struct sockaddr *saddr = reinterpret_cast<const struct sockaddr *>(&sin);
  err = ::connect(sd, saddr, sizeof(struct sockaddr));
  if (err == -1) {
    perror(NULL);
    assert(!"connect() failed");
  }

  struct aiocb *aio = new aiocb();
  memset(aio, 0, sizeof(struct aiocb));

  char *buf = new char[3];
  buf[0] = 'a';
  buf[1] = 'b';
  buf[2] = 'c';
  aio->aio_fildes = sd;
  aio->aio_buf = buf;
  aio->aio_nbytes = 3;

  aio->aio_sigevent.sigev_notify = SIGEV_SIGNAL;
  aio->aio_sigevent.sigev_signo = SIGIO;
  aio->aio_sigevent.sigev_value.sival_ptr = &aio;

  struct sigaction sig_act;

  sigemptyset(&sig_act.sa_mask);
  sig_act.sa_flags = SA_SIGINFO;
  sig_act.sa_sigaction = aio_completion_handler;

  sigaction(SIGIO, &sig_act, NULL);

  errno = 0;
  int ret = aio_write(aio);
  if (ret == -1) {
    perror(NULL);
  }  
  assert(ret != -1);  
}
Run Code Online (Sandbox Code Playgroud)

更新(2010 年 2 月):OSX 根本不支持套接字上的 AIO。真糟糕!

小智 1

我的代码与您在 10.6.2 上的代码非常相似(但写入文件),工作没有任何问题 - 所以可以做您正在尝试的事情。

只是出于好奇,您对 SIGIO 常量使用什么值?我发现 OS X 中的无效值会导致 aio_write 失败 - 所以我总是传递 SIGUSR1。

也许检查 sigaction() 的返回值来验证信号详细信息?