aio_cancel - Linux


aio_cancel is a kernel function that cancels asynchronous I/O operations submitted to the Linux kernel using the aio_write or aio_read functions. It allows users to terminate incomplete asynchronous I/O operations for various reasons, including error handling or resource management.


int aio_cancel(int fd, struct aiocb *aiocbp)




Cancel a specific asynchronous read operation:

#include <libaio.h>

int main() {
  struct aiocb aiocb;
  int fd = open("file.txt", O_RDONLY);
  memset(&aiocb, 0, sizeof(aiocb));
  aiocb.aio_fildes = fd;
  aiocb.aio_buf = malloc(1024);
  aiocb.aio_nbytes = 1024;

  // Issue asynchronous read
  if (aio_read(&aiocb) < 0) {
    perror("Error reading file");
    return -1;

  // Cancel the read operation
  if (aio_cancel(fd, &aiocb) < 0) {
    perror("Error canceling I/O operation");
    return -1;

  return 0;

Cancel all asynchronous I/O operations associated with a file descriptor:

#include <sys/ioctl.h>
#include <unistd.h>

int main() {
  int fd = open("file.txt", O_RDWR);

  // Cancel all I/O operations for the file descriptor
  if (ioctl(fd, AIO_CANCEL, NULL) < 0) {
    perror("Error canceling I/O operations");
    return -1;

  return 0;

Common Issues

  • EINPROGRESS: The specified I/O operation is still in progress and cannot be canceled.
  • EINVAL: The file descriptor or aiocb structure is invalid.
  • EBADF: The file descriptor is not open for reading or writing.


aio_cancel can be integrated with other Linux commands or tools for more complex tasks. For example, it can be used with the epoll or select functions to monitor asynchronous I/O operations and cancel them if necessary.

Related Commands

  • aio_write
  • aio_read
  • aio_suspend
  • aio_resume