source: example/io/cat.c@ 2ae845e9

Last change on this file since 2ae845e9 was f0d67e5, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

Restored io examples to example folder

  • Property mode set to 100644
File size: 2.0 KB
Line 
1/*
2This is a simple "cat" example that uses io_uring in IORING_SETUP_IOPOLL mode.
3It demonstrates the bare minimum needed to use io_uring in polling mode.
4It uses liburing for simplicity.
5*/
6
7
8#ifndef _GNU_SOURCE
9#define _GNU_SOURCE
10#endif
11
12#include <fcntl.h>
13#include <liburing.h>
14#include <stdio.h>
15#include <string.h>
16#include <unistd.h>
17
18struct io_uring ring;
19
20__attribute__((aligned(1024))) char data[1024];
21
22int main(int argc, char * argv[]) {
23 if(argc != 2) {
24 printf("usage: %s FILE - prints file to console.\n", argv[0]);
25 return 1;
26 }
27
28 int fd = open(argv[1], O_DIRECT);
29 if(fd < 0) {
30 printf("Could not open file %s.\n", argv[1]);
31 return 2;
32 }
33
34 /* prep the array */
35 struct iovec iov = { data, 1024 };
36
37 /* init liburing */
38 io_uring_queue_init(256, &ring, IORING_SETUP_IOPOLL);
39
40 /* declare required structs */
41 struct io_uring_sqe * sqe;
42 struct io_uring_cqe * cqe;
43
44 /* get an sqe and fill in a READV operation */
45 sqe = io_uring_get_sqe(&ring);
46 io_uring_prep_readv(sqe, fd, &iov, 1, 0);
47 // io_uring_prep_read(sqe, fd, data, 1024, 0);
48
49 sqe->user_data = (uint64_t)(uintptr_t)data;
50
51 /* tell the kernel we have an sqe ready for consumption */
52 io_uring_submit(&ring);
53
54 /* wait for the sqe to complete */
55 int ret = io_uring_wait_cqe(&ring, &cqe);
56
57 /* read and process cqe event */
58 if(ret == 0) {
59 char * out = (char *)(uintptr_t)cqe->user_data;
60 signed int len = cqe->res;
61 io_uring_cqe_seen(&ring, cqe);
62
63 if(len > 0) {
64 printf("%.*s", len, out);
65 }
66 else if( len < 0 ) {
67 fprintf(stderr, "readv/read returned error : %s\n", strerror(-len));
68 }
69 }
70 else {
71 printf("%d\n", ret);
72 io_uring_cqe_seen(&ring, cqe);
73 }
74
75 io_uring_queue_exit(&ring);
76
77 close(fd);
78}
Note: See TracBrowser for help on using the repository browser.