Thread: Using asynchoronous I/O : readv and writev

  1. #1
    Registered User
    Join Date
    Aug 2008
    Posts
    22

    Using asynchoronous I/O : readv and writev

    Hi,
    I am trying to write a program to copy files using aync I/O in unix.
    I have written this code :

    Code:
    #include<stdio.h>
    #include<sys/types.h>
    #include<sys/uio.h>
    #include<unistd.h>
    
    int main(int argc,char *argv[])
    {
    	int fs,fd;
    	ssize_t bytes_read,bytes_written;
    	char buf[3][50];
    	int iovcnt;
    	struct iovec iov[3];
    	int i;
    	fs=open(argv[1],O_RDONLY);
    	fd=open(argv[2],O_RDWR | O_CREAT);
    	for(i=0;i<3;i++)
    	{
    		iov[i].iov_base=buf[i];
    		iov[i].iov_len=sizeof(buf[i]);
    	}
    	iovcnt=sizeof(iov)/sizeof(struct iovec);
    	while((bytes_read=readv(fs,iov,iovcnt))!=-1)  			
    		if((bytes_written=writev(fd,iov,iovcnt))==-1)
    			printf("Write error\n");
    	close(fs);
    	close(fd);
    	return 0;
    }
    The contents of source file are getting copied to the destination but some junk is also appended with it. I suspect the problem is because of the buffers used for writing. The extra space in the buffers have junk which is written to the file. Can anyone suggest a fix for this?

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    You need to adjust the I/O vectors so that they don't claim to contain sizeof(buf[i]) bytes when they only contain a total of bytes_read bytes.

    Why the scatter/gather operation anyway?

    Oh yeah, that's not asynchronous I/O, by the way. That's perfectly synchronous. Only the scatter/gather operation is different from a simple read/write loop. And it only makes things difficult for you.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Using writev() instead of write() on sockets?
    By cpjust in forum C Programming
    Replies: 0
    Last Post: 11-22-2007, 02:11 PM