Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 14.5 Asynchronous I/O 517


if (argc != 3)
err_quit("usage: rot13 infile outfile");
if ((ifd = open(argv[1], O_RDONLY)) < 0)
err_sys("can’t open %s", argv[1]);
if ((ofd = open(argv[2], O_RDWR|O_CREAT|O_TRUNC, FILE_MODE)) < 0)
err_sys("can’t create %s", argv[2]);

while ((n = read(ifd, buf, BSZ)) > 0) {
for (i = 0; i < n; i++)
buf[i] = translate(buf[i]);
if ((nw = write(ofd, buf, n)) != n) {
if (nw < 0)
err_sys("write failed");
else
err_quit("short write (%d/%d)", nw, n);
}
}

fsync(ofd);
exit(0);
}

Figure 14.20Tr anslate a file using ROT- 13

The I/O portion of the program is straightforward: we read a block from the input
file, translate it, and then write the block to the output file.We repeat this until we hit
the end of file andreadreturns zero. The program in Figure14.21 shows how to
perform the same task using the equivalent asynchronous I/O functions.
#include "apue.h"
#include <ctype.h>
#include <fcntl.h>
#include <aio.h>
#include <errno.h>

#define BSZ 4096
#define NBUF 8

enum rwop {
UNUSED = 0,
READ_PENDING = 1,
WRITE_PENDING = 2
};

struct buf {
enum rwop op;
int last;
struct aiocb aiocb;
unsigned char data[BSZ];
};

struct buf bufs[NBUF];
Free download pdf