# Example for aio_cancel Function

The following example illustrates how aio_cancel() function can be used.

    int aio_ex_4(HANDLE fd)
    {
      static struct aiocb   aio;
      static struct aiocb  *aio_list[] = {&aio};
      int    ret;
      char  *dat = "Hello from Ex-4\n";

     printf("AIO_CANCELED=%d AIO_NOTCANCELED=%d\n",
     AIO_CANCELED,   AIO_NOTCANCELED);

    /* Data initialization and asynchronously writing */

     IC_AIO_DATA_INIT(aio, fd, dat, strlen(dat), 0);
     if (aio_write(&aio) == -1) return errno;

     ret = aio_cancel(fd, &aio);
     if ( ret == AIO_NOTCANCELED ) {
     fprintf(stderr, "ERRNO=%d STR=%s\n", ret, strerror(ret));
     ret = aio_suspend(aio_list, 1, NULL);
     if (ret == -1) return errno;}

     ret = aio_cancel(fd, &aio);
     if ( ret == AIO_CANCELED )
     fprintf(stderr, "ERRNO=%d STR=%s\n", ret, strerror(ret));
     else if (ret) return ret;

     return 0;
    }/* aio_ex_4 */

Result upon execution:

    -bash-3.00$ ./a.out
    AIO_CANCELED=0 AIO_NOTCANCELED=1
    ERRNO=1 STR=Operation not permitted
    -bash-3.00$ cat dat
    Hello from Ex-4
    -bash-3.00$

Remarks:

1. In the example, the`IC_AIO_DATA_INIT` is defined as follows:

       #define IC_AIO_DATA_INIT(_aio, _fd, _dat, _len, _off)\
        {memset(&_aio, 0, sizeof(_aio)); \
        _aio.aio_fildes = _fd;          \
        _aio.aio_buf    = _dat;         \
        _aio.aio_nbytes = _len;         \
        _aio.aio_offset = _off;}

2. The file descriptor `fd` is obtained as:

       HANDLE fd = CreateFile("dat",
         GENERIC_READ | GENERIC_WRITE,
         FILE_SHARE_READ,
         NULL,
         OPEN_ALWAYS,
         FILE_ATTRIBUTE_NORMAL/*|FILE_FLAG_OVERLAPPED*/,
         NULL);

Parent topic: Intel's C++ Asynchronous I/O Library for Windows* Operating Systems

## See Also

aio_cancel()