Last active
August 19, 2025 00:54
-
-
Save kraj/d2b3f19e68d4c1f53155bd6b6768879b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// preadv_pwritev_test.c | |
// run like below | |
// strace -ff -vv -o trace.log -e trace=pread64,preadv,pwrite64,pwritev ./a.out | |
#define _GNU_SOURCE | |
#include <fcntl.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <sys/uio.h> | |
int main(void) { | |
const char *fname = "testfile.bin"; | |
int fd = open(fname, O_CREAT | O_RDWR, 0644); | |
if (fd < 0) { | |
perror("open"); | |
return 1; | |
} | |
// Write some data at offset 0 | |
const char *msg = "hello world\n"; | |
ssize_t w = pwrite(fd, msg, strlen(msg), 0); | |
if (w < 0) { perror("pwrite"); return 1; } | |
// Read it back with pread64 at offset 0 | |
char buf[64]; | |
ssize_t r = pread(fd, buf, sizeof(buf)-1, 0); | |
if (r < 0) { perror("pread"); return 1; } | |
buf[r] = '\0'; | |
printf("pread got: %s", buf); | |
// Now do a vectored write at offset 100 | |
struct iovec iovw[2]; | |
iovw[0].iov_base = "abc"; | |
iovw[0].iov_len = 3; | |
iovw[1].iov_base = "XYZ\n"; | |
iovw[1].iov_len = 4; | |
ssize_t wv = pwritev(fd, iovw, 2, 100); | |
if (wv < 0) { perror("pwritev"); return 1; } | |
// And a vectored read at offset 100 | |
char buf1[8], buf2[8]; | |
struct iovec iovr[2]; | |
iovr[0].iov_base = buf1; | |
iovr[0].iov_len = sizeof(buf1); | |
iovr[1].iov_base = buf2; | |
iovr[1].iov_len = sizeof(buf2); | |
ssize_t rv = preadv(fd, iovr, 2, 100); | |
if (rv < 0) { perror("preadv"); return 1; } | |
printf("preadv got: %.*s%.*s", (int)iovr[0].iov_len, buf1, | |
(int)iovr[1].iov_len, buf2); | |
close(fd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment