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)