xref: /DragonOS/user/apps/test_dup3/main.c (revision 1df85daf8f1b4426fe09d489d815997cdf989a87)
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <fcntl.h>
4 
5 int main() {
6     int fd = open("/history_commands.txt", O_RDONLY);
7     if (fd < 0) {
8         perror("Failed to open file");
9         return 1;
10     }
11 
12     int new_fd = 777;
13     int rt = dup3(fd, new_fd, O_CLOEXEC);
14     if (rt < 0) {
15         perror("Failed to duplicate file descriptor with flags");
16     }
17 
18     char buffer[100];
19     int bytes_read = read(new_fd, buffer, sizeof(buffer));
20     if (bytes_read < 0) {
21         perror("Failed to read data");
22         return 1;
23     }
24 
25     printf("Data:\n %.*s\n", bytes_read, buffer);
26 
27     close(fd);
28     close(new_fd);
29     return 0;
30 }