• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <sys/sendfile.h>
21 
22 #include "test.h"
23 
24 const char *fromfile = "/data/tests/libc-test/src/fromfile.txt";
25 const char *tofile = "/data/tests/libc-test/src/tofile.txt";
26 
27 /**
28  * @tc.name      : sendfile_0100
29  * @tc.desc      : transfer data between file descriptors
30  * @tc.level     : Level 0
31  */
sendfile_0100(void)32 void sendfile_0100(void)
33 {
34     FILE *f = fopen(fromfile, "w+");
35     const char src[] = "A";
36     fwrite(src, strlen(src), 1, f);
37     fclose(f);
38 
39     f = fopen(tofile, "w+");
40     fclose(f);
41 
42     int fromfd = open(fromfile, O_RDONLY);
43     if (fromfd < 0) {
44         t_error("%s failed: open. fromfd = %d\n", __func__, fromfd);
45     }
46 
47     int tofd = open(tofile, O_WRONLY | O_CREAT);
48     if (tofd < 0) {
49         t_error("%s failed: open. tofd = %d\n", __func__, tofd);
50     }
51 
52     off_t off = 0;
53     int result = sendfile(tofd, fromfd, &off, 1);
54     if (result < 0) {
55         t_error("%s failed: sendfile. result = %d\n", __func__, result);
56     }
57 
58     close(fromfd);
59     close(tofd);
60 
61     f = fopen(tofile, "r");
62     char buf[sizeof(src) + 1] = {0};
63     fread(buf, 1, strlen(src), f);
64     fclose(f);
65 
66     if (strcmp(src, buf)) {
67         t_error("%s failed: sendfile. buf = %s\n", __func__, buf);
68     }
69 
70     remove(fromfile);
71     remove(tofile);
72 }
73 
74 /**
75  * @tc.name      : sendfile_0200
76  * @tc.desc      : transfer data between invalid file descriptors
77  * @tc.level     : Level 2
78  */
sendfile_0200(void)79 void sendfile_0200(void)
80 {
81     int fromfd = -1;
82     int tofd = -1;
83     off_t off = 0;
84 
85     int result = sendfile(tofd, fromfd, &off, 1);
86     if (result >= 0) {
87         t_error("%s failed: sendfile. result = %d\n", __func__, result);
88     }
89 
90     if (errno != EBADF) {
91         t_error("%s failed: sendfile. errno = %d\n", __func__, errno);
92     }
93 }
94 
main(int argc,char * argv[])95 int main(int argc, char *argv[])
96 {
97     sendfile_0100();
98     sendfile_0200();
99 
100     return t_status;
101 }
102