-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread_large_file_example.cc
More file actions
79 lines (66 loc) · 2.27 KB
/
Copy pathread_large_file_example.cc
File metadata and controls
79 lines (66 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// ============================================================================
// Example: Chunked asynchronous file read (large file streaming)
//
// Demonstrates: Task chaining via handler, fd_offset for seek, KernelBuf
// Resize, repeat-forever vs one-shot patterns.
// ============================================================================
#include <fcntl.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <talon/async_io.hpp>
using namespace talon;
using namespace talon::task;
// Global IOHandler so the handler can re-submit chains.
static IOHandler io;
// Each invocation reads one chunk, prints it, and creates the next chunk.
void ReadChunkHandler(KernelBuf* buf) {
int bytes = buf->BytesTransferred();
int fd = buf->ActiveFileDescriptor();
if (bytes < 0) {
fprintf(stderr, "ReadChunkHandler: error fd=%d: %s\n",
fd, strerror(-bytes));
close(fd);
io.RequestShutdown();
return;
}
if (bytes == 0) {
printf("\n--- EOF (fd=%d) ---\n", fd);
close(fd);
io.RequestShutdown();
return;
}
printf("[chunk fd=%d offset=%lld size=%d]\n",
fd, (long long)buf->FdOffset(), bytes);
for (int i = 0; i < bytes; i++) putchar(buf->Data()[i]);
// Chain the next chunk.
int64_t next_offset = buf->FdOffset() + bytes;
auto* next = CreateTaskWithHandler(fd, ReadChunkHandler);
next->SetTaskType(TaskType::kRead);
next->Buffer()->Resize(32);
next->Buffer()->SetFdOffset(next_offset);
io.AddTask(next);
}
int main() {
if (!io.Initialized()) {
fprintf(stderr, "IOHandler init failed: %s\n",
io.InitError().c_str());
return EXIT_FAILURE;
}
int fd = open("./include/talon/async_io.hpp", O_RDONLY);
if (fd < 0) { perror("open"); return EXIT_FAILURE; }
auto* task = CreateTaskWithHandler(fd, ReadChunkHandler);
task->SetTaskType(TaskType::kRead);
task->SetDebugStr("chunked_read");
task->Buffer()->Resize(32);
task->Buffer()->SetFdOffset(0);
if (!io.AddTask(task)) {
fprintf(stderr, "AddTask failed\n");
close(fd);
return EXIT_FAILURE;
}
io.Join();
printf("\nChunked file read complete.\n");
return 0;
}