xref: /aosp_15_r20/external/liburing/test/pipe-eof.c (revision 25da2bea747f3a93b4c30fd9708b0618ef55a0e6)
1 /* SPDX-License-Identifier: MIT */
2 
3 /*
4  * Test that closed pipe reads returns 0, instead of waiting for more
5  * data.
6  */
7 #include <errno.h>
8 #include <stdio.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <pthread.h>
12 #include <string.h>
13 #include "liburing.h"
14 
15 #define BUFSIZE	512
16 
17 struct data {
18 	char *str;
19 	int fds[2];
20 };
21 
t(void * data)22 static void *t(void *data)
23 {
24 	struct data *d = data;
25 	int ret;
26 
27 	strcpy(d->str, "This is a test string");
28 	ret = write(d->fds[1], d->str, strlen(d->str));
29 	close(d->fds[1]);
30 	if (ret < 0)
31 		perror("write");
32 
33 	return NULL;
34 }
35 
main(int argc,char * argv[])36 int main(int argc, char *argv[])
37 {
38 	static char buf[BUFSIZE];
39 	struct io_uring ring;
40 	pthread_t thread;
41 	struct data d;
42 	int ret;
43 
44 	if (pipe(d.fds) < 0) {
45 		perror("pipe");
46 		return 1;
47 	}
48 	d.str = buf;
49 
50 	io_uring_queue_init(8, &ring, 0);
51 
52 	pthread_create(&thread, NULL, t, &d);
53 
54 	while (1) {
55 		struct io_uring_sqe *sqe;
56 		struct io_uring_cqe *cqe;
57 
58 		sqe = io_uring_get_sqe(&ring);
59 		io_uring_prep_read(sqe, d.fds[0], buf, BUFSIZE, 0);
60 		ret = io_uring_submit(&ring);
61 		if (ret != 1) {
62 			fprintf(stderr, "submit: %d\n", ret);
63 			return 1;
64 		}
65 		ret = io_uring_wait_cqe(&ring, &cqe);
66 		if (ret) {
67 			fprintf(stderr, "wait: %d\n", ret);
68 			return 1;
69 		}
70 
71 		if (cqe->res < 0) {
72 			fprintf(stderr, "Read error: %s\n", strerror(-cqe->res));
73 			return 1;
74 		}
75 		if (cqe->res == 0)
76 			break;
77 		io_uring_cqe_seen(&ring, cqe);
78 	}
79 
80 	pthread_join(thread, NULL);
81 	io_uring_queue_exit(&ring);
82 	return 0;
83 }
84