2

次のコード:

#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;
}

Linux (Ubuntu 9.10、-lrt でコンパイル) で正常に動作し、印刷

1
1

しかし、OS X では失敗します (10.6.6 と 10.6.5、2 台のマシンでテストしました):

1
35, readerr

これは、OS X のライブラリ エラーが原因である可能性がありますか、それとも何か間違っていますか?

4

2 に答える 2

5

aio_return(2)非同期 I/O 操作ごとに 1 回だけ呼び出す必要があります。そのマニュアルページのメモによると、そうしないとリソースがリークし、明らかに問題の原因にもなります。呼び出しaio_suspendて I/O が完了するのを待った後、次のように呼び出しaio_returnて読み取ったバイト数を取得してください。

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);
}

また、aio_read(2)man ページの次の重要な注意事項にも注意してください (強調は私のものです)。

によってポイントされる非同期 I/O コントロール ブロック構造体と、その構造体aiocbpのメンバーが参照するバッファーはaiocbp->aio_buf、操作が完了するまで有効なままでなければなりません。このため、これらのオブジェクトに auto (スタック) 変数を使用することはお勧めできません

偽のコンテキスト情報がカーネルに渡されないように、呼び出しの前に非同期 I/O コントロール バッファーaiocbpをゼロにする必要が あります。aio_read()

于 2011-01-12T06:07:50.433 に答える
0

をゼロにしてみてくださいstruct aiocb aio

マニュアルには次のように書かれています。

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.
于 2011-01-12T06:02:38.023 に答える