// Ivan Novick // Aug 26, 2009 // Direct IO to a device with no filesystem #define _GNU_SOURCE #include #include #include #include #include #include #define BUFSIZE 4096 #define LOCATION 4096*16 #define DATA_SIZE 100 int main(int argc, char** argv) { int fd; int r; int i; // allocate blocks that are aligned for direct IO char* buf = memalign(BUFSIZE, BUFSIZE); char* readbuf = memalign(BUFSIZE, BUFSIZE); memset(buf, 0, BUFSIZE); memset(readbuf, 0, BUFSIZE); for(i = 0; i < DATA_SIZE ; ++i){ buf[i] = i; } // open a device fd = open("/dev/sdc", O_DIRECT|O_WRONLY, 0); if (fd < 0) { fprintf(stderr, "return from open %d\n", fd); return 1; } // seek to a position in the device r = lseek(fd, LOCATION, SEEK_SET); if (r < 0) { fprintf(stderr, "return from lseek unexpected -- %d -- %s\n", r, strerror(errno)); return 1; } // write the buffer to the device r = write(fd, buf, BUFSIZE); if (r != BUFSIZE) { fprintf(stderr, "return from write unexpected -- %d -- %s\n", r, strerror(errno)); return 1; } close(fd); // reopen the device for reading fd = open("/dev/sdc", O_RDONLY, 0); if (fd < 0) { fprintf(stderr, "return from open %d\n", fd); return 1; } // seek to the position where the data should be r = lseek(fd, LOCATION, SEEK_SET); if (r < 0) { fprintf(stderr, "return from lseek unexpected -- %d -- %s\n", r, strerror(errno)); return 1; } // read the data from the device r = read(fd, readbuf, BUFSIZE); close(fd); printf("read %d bytes from device\n", r); for (i = 0; i < DATA_SIZE; ++i){ printf("%d ", readbuf[i]); } printf("\n"); // free the memory free(buf); free(readbuf); return 0; }