-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom_handler_example.cc
More file actions
67 lines (55 loc) · 1.99 KB
/
Copy pathcustom_handler_example.cc
File metadata and controls
67 lines (55 loc) · 1.99 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
// ============================================================================
// Example: Custom handler with user-provided arguments
//
// Demonstrates: CreateTaskWithHandler with extra user arguments,
// FunctionTraits compile-time validation, multi-file read.
// ============================================================================
#include <fcntl.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <unistd.h>
#include <talon/async_io.hpp>
using namespace talon;
using namespace talon::task;
static IOHandler io;
// Handler with extra user arguments: file_id (string) and chunk_number (int).
// Signature must be: void(KernelBuf*, UserArg1, UserArg2, ...)
void AnnotatedReadHandler(KernelBuf* buf, const std::string& file_id,
int chunk_number) {
int bytes = buf->BytesTransferred();
int fd = buf->ActiveFileDescriptor();
printf("[%s chunk=%d] fd=%d, bytes=%d\n",
file_id.c_str(), chunk_number, fd, bytes);
if (bytes <= 0) {
close(fd);
io.RequestShutdown();
return;
}
printf("[%s chunk=%d] data: %.*s\n",
file_id.c_str(), chunk_number, bytes, buf->Data());
close(fd);
io.RequestShutdown();
}
int main() {
if (!io.Initialized()) {
fprintf(stderr, "IOHandler init failed: %s\n",
io.InitError().c_str());
return EXIT_FAILURE;
}
int fd = open(__FILE__, O_RDONLY);
if (fd < 0) { perror("open"); return EXIT_FAILURE; }
// Bind extra arguments: file_id="source", chunk_number=1.
// CreateTaskWithHandler handles argument binding via std::bind.
auto* task = CreateTaskWithHandler(
fd, AnnotatedReadHandler,
std::string("source_file"), // user arg 1
1); // user arg 2
task->SetTaskType(TaskType::kRead);
task->SetDebugStr("custom_handler_demo");
io.AddTask(task);
io.Join();
printf("Custom handler demo complete.\n");
return 0;
}