LWN.net Logo

Async I/O

Async I/O

Posted Apr 8, 2009 7:40 UTC (Wed) by bojan (subscriber, #14302)
In reply to: Async I/O by bojan
Parent article: Linux Storage and Filesystem workshop, day 1

Quick and dirty - probably has more bugs then lines, but you'll get the picture.

Compile and link with: gcc -Wall -O2 -g -o a a.c -lrt

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>
#include <aio.h>

#define BUF_SIZE 50

static int count=0;

void whack(int signum,siginfo_t *info,void *context){
  if(!--count)
    unlink("foo~");
}

int main(int argc,char **argv){
  int fd;
  ssize_t rl;
  char *buf=malloc(BUF_SIZE);
  struct aiocb *cb=calloc(1,sizeof(*cb));
  struct sigevent *se=calloc(1,sizeof(*se));
  struct sigaction *act=calloc(1,sizeof(*act));

  /* XXX this is just a demo, no error checking */

  /* AIO control block defaults */
  cb->aio_sigevent.sigev_notify=SIGEV_SIGNAL;
  cb->aio_sigevent.sigev_signo=SIGRTMIN;

  /* signal handler */
  act->sa_flags=SA_SIGINFO;
  act->sa_sigaction=whack;
  sigaction(SIGRTMIN,act,NULL);

  /* see if foo~ exists and restore */
  if(!access("foo~",F_OK|R_OK|W_OK))
    rename("foo~","foo"); 

  /* back it up if required */
  if(access("foo~",F_OK|R_OK|W_OK))
    link("foo","foo~");

  /* read existing file */
  fd=open("foo",O_RDONLY);
  rl=read(fd,buf,BUF_SIZE);
  close(fd);

  /* write to new file and initiate sync */
  fd=open("foo.new",O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  write(fd,buf,rl);
  cb->aio_fildes=fd;
  count++;
  aio_fsync(O_SYNC,cb);
  close(fd);

  /* rename new file into the existing one */
  rename("foo.new","foo");

  free(act);
  free(se);
  free(cb);
  free(buf);

  return 0;
}


(Log in to post comments)

Async I/O

Posted Apr 8, 2009 8:03 UTC (Wed) by bojan (subscriber, #14302) [Link]

Of course, this won't work for two programs reading/modifying the same config file.

Why all the runtime allocations? (off-topic)

Posted Apr 9, 2009 4:17 UTC (Thu) by pr1268 (subscriber, #24648) [Link]

This is going way off-topic, but why all the runtime allocations in your sample program? Malloc(3), calloc(3), and free(3) are horribly expensive, relatively speaking. Automatic/static storage for those structs and that char buffer would be substantially faster.

Why all the runtime allocations? (off-topic)

Posted Apr 9, 2009 6:14 UTC (Thu) by bojan (subscriber, #14302) [Link]

Just being lazy to call memset(), I guess...

Copyright © 2013, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds