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 #include <stdio.h>
16 #include <stdlib.h>
17 #include <errno.h>
18 #include <unistd.h>
19 #include <fcntl.h>
20 #include <string.h>
21 #include "beget_ext.h"
22 #include "fd_holder.h"
23
24 #define BUFFER_LENGTH 5
25 #define FD_COUNT 2
26 #define SLEEP_TIME 3
27 #define ENV_FD_HOLD_PREFIX "OHOS_FD_HOLD_"
28
SaveFds(const char * serviceName,int argc,char ** argv)29 static void SaveFds(const char *serviceName, int argc, char **argv)
30 {
31 int fds[10];
32 int i;
33 for (i = 0; i < argc; i++) {
34 BEGET_LOGI("Opening %s \n", argv[i]);
35 fds[i] = open(argv[i], O_APPEND | O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
36 if (fds[i] < 0) {
37 BEGET_LOGI("Failed to open file %s\n", argv[i]);
38 break;
39 }
40 (void)write(fds[i], "hello", BUFFER_LENGTH);
41 }
42 int fdCount = i;
43 BEGET_LOGI("fdCount = %d\n", fdCount);
44 if (fdCount <= 0) {
45 BEGET_LOGE("Invalid fds for hold, abort\n");
46 return;
47 }
48 int ret = ServiceSaveFd(serviceName, fds, (size_t)fdCount);
49 if (ret < 0) {
50 BEGET_LOGE("Request init save fds failed\n");
51 } else {
52 BEGET_LOGI("Request init save fds done\n");
53 }
54 }
55
56
main(int argc,char ** argv)57 int main(int argc, char **argv)
58 {
59 size_t outfdCount = 0;
60 int *fds = ServiceGetFd("fd_holder_test", &outfdCount);
61 if (fds == NULL) {
62 BEGET_LOGE("Cannot get fds, maybe first time\n");
63 } else {
64 for (size_t i = 0; i < outfdCount; i++) {
65 int fd = fds[i];
66 if (write(fd, "world", BUFFER_LENGTH) < 0) {
67 BEGET_LOGE("Failed to write content to fd: %d, err = %d", fd, errno);
68 }
69 close(fd);
70 }
71 free(fds);
72 outfdCount = 0;
73 while (1) {
74 sleep(SLEEP_TIME);
75 }
76 }
77 char *files[] = {"/data/test/1", "/data/test/2"};
78 SaveFds("fd_holder_test", FD_COUNT, (char **)files);
79 while (1) {
80 sleep(SLEEP_TIME);
81 }
82 return 0;
83 }
84