Skip to content

Instantly share code, notes, and snippets.

@boldfield
Created December 19, 2018 16:31
Show Gist options
  • Save boldfield/ebb6b15e723405b602bc2d1397c7f577 to your computer and use it in GitHub Desktop.
Save boldfield/ebb6b15e723405b602bc2d1397c7f577 to your computer and use it in GitHub Desktop.
Direct IO testing...
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define HDD_PATH "/dev/sdc"
#define BLOCK_SIZE 1
int main(int argc, char *argv[]) {
printf("opening %s\n", HDD_PATH);
//int fd = open(HDD_PATH, O_RDWR | O_DIRECT | O_SYNC);
int fd = open(HDD_PATH, O_RDWR | O_SYNC);
if (fd < 0) {
printf("Failed to open the fd, exiting\n");
return 1;
}
printf("FD %d opened for dev %s\n", fd, HDD_PATH);
char* testStringIn = "Mary had a little lamb,\nlittle lamb,\nlittle lamb.\nMary had a little lamb\nwho's fleece was white as snow";
size_t testStringLen = strlen(testStringIn);
int blk_cnt = testStringLen / BLOCK_SIZE + 1;
printf("String occupies %d blocks for a total size of %d bytes.\n", blk_cnt, blk_cnt * BLOCK_SIZE);
char* inputBuffer = (char *)malloc(BLOCK_SIZE * blk_cnt);
memset(inputBuffer, 0, BLOCK_SIZE * blk_cnt);
memcpy(inputBuffer, testStringIn, testStringLen);
printf("\n\nWriting test string of size %d to the drive:\n%s\n\n", (int)testStringLen, testStringIn);
int success = pwrite(fd, inputBuffer, BLOCK_SIZE * blk_cnt, 0);
if (success < 0) {
printf("Write failed! %d\n", success);
} else {
char* outputBuffer = (char *)malloc(BLOCK_SIZE * blk_cnt);
memset(outputBuffer, 0, BLOCK_SIZE * blk_cnt);
size_t bytesRead = pread(fd, outputBuffer, BLOCK_SIZE * blk_cnt, 0);
printf("\n\nRead %d bytes from the disk.\n", (int)bytesRead);
printf("Read test string from disk:\n\n%s\n\n", outputBuffer);
free(outputBuffer);
}
printf("closing fd for %s\n", HDD_PATH);
close(fd);
free(inputBuffer);
return 0;
}
@boldfield
Copy link
Author

Output:

$ ./main
opening /dev/sdc
FD 3 opened for dev /dev/sdc
String occupies 104 blocks for a total size of 104 bytes.


Writing test string of size 103 to the drive:
Mary had a little lamb,
little lamb,
little lamb.
Mary had a little lamb
who's fleece was white as snow



Read 104 bytes from the disk.
Read test string from disk:

Mary had a little lamb,
little lamb,
little lamb.
Mary had a little lamb
who's fleece was white as snow

closing fd for /dev/sdc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment