Question

The following code:

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <aio.h>
#include <errno.h>

int main (int argc, char const *argv[])
{
  char name[] = "abc";
  int fdes;
  if ((fdes = open(name, O_RDWR | O_CREAT, 0600 )) < 0)
    printf("%d, create file", errno);

  int buffer[] = {0, 1, 2, 3, 4, 5};
  if (write(fdes, &buffer, sizeof(buffer)) == 0){
    printf("writerr\n");
  }

  struct aiocb aio;
  int n = 2;
  while (n--){
    aio.aio_reqprio = 0;
    aio.aio_fildes = fdes;
    aio.aio_offset = sizeof(int);
    aio.aio_sigevent.sigev_notify = SIGEV_NONE; 

    int buffer2;
    aio.aio_buf = &buffer2;
    aio.aio_nbytes = sizeof(buffer2);

    if (aio_read(&aio) != 0){
      printf("%d, readerr\n", errno);
    }else{
      const struct aiocb *aio_l[] = {&aio};
      if (aio_suspend(aio_l, 1, 0) != 0){
         printf("%d, suspenderr\n", errno);
      }else{
        printf("%d\n", *(int *)aio.aio_buf);
      }
    }
  }

  return 0;
}

Works fine on Linux (Ubuntu 9.10, compiled with -lrt), printing

1
1

But fails on OS X (10.6.6 and 10.6.5, I've tested it on two machines):

1
35, readerr

Is this possible that this is due to some library error on OS X, or am I doing something wrong?

Was it helpful?

Solution

You need to call aio_return(2) exactly once for each asynchronous I/O operation. According to the note on that man page, failure to do so will leak resources, and it apparently also causes your problem. After you call aio_suspend to wait for the I/O to complete, make sure to call aio_return to get the number of bytes read, e.g.:

const struct aiocb *aio_l[] = {&aio};
if (aio_suspend(aio_l, 1, 0) != 0)
{
  printf("aio_suspend: %s\n", strerror(errno));
}
else
{
  printf("successfully read %d bytes\n", (int)aio_return(&aio));
  printf("%d\n", *(int *)aio.aio_buf);
}

Also bear in mind these important notes from the aio_read(2) man page (emphasis mine):

The Asynchronous I/O Control Block structure pointed to by aiocbp and the buffer that the aiocbp->aio_buf member of that structure references must remain valid until the operation has completed. For this reason, use of auto (stack) variables for these objects is discouraged.

The asynchronous I/O control buffer aiocbp should be zeroed before the aio_read() call to avoid passing bogus context information to the kernel.

OTHER TIPS

Try zeroing the struct aiocb aio?

The manual reads:

RESTRICTIONS
[...]
     The asynchronous I/O control buffer aiocbp should be zeroed before the
     aio_read() call to avoid passing bogus context information to the kernel.
[...]
BUGS
     Invalid information in aiocbp->_aiocb_private may confuse the kernel.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top