1 /*
2 *
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include <grpc/support/port_platform.h>
20
21 #ifdef GPR_POSIX_TMPFILE
22
23 #include "src/core/lib/gpr/tmpfile.h"
24
25 #include <errno.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29
30 #include <grpc/support/alloc.h>
31 #include <grpc/support/log.h>
32 #include <grpc/support/string_util.h>
33
34 #include "src/core/lib/gpr/string.h"
35
gpr_tmpfile(const char * prefix,char ** tmp_filename)36 FILE* gpr_tmpfile(const char* prefix, char** tmp_filename) {
37 FILE* result = nullptr;
38 char* filename_template;
39 int fd;
40
41 if (tmp_filename != nullptr) *tmp_filename = nullptr;
42
43 gpr_asprintf(&filename_template, "/tmp/%s_XXXXXX", prefix);
44 GPR_ASSERT(filename_template != nullptr);
45
46 fd = mkstemp(filename_template);
47 if (fd == -1) {
48 gpr_log(GPR_ERROR, "mkstemp failed for filename_template %s with error %s.",
49 filename_template, strerror(errno));
50 goto end;
51 }
52 result = fdopen(fd, "w+");
53 if (result == nullptr) {
54 gpr_log(GPR_ERROR, "Could not open file %s from fd %d (error = %s).",
55 filename_template, fd, strerror(errno));
56 unlink(filename_template);
57 close(fd);
58 goto end;
59 }
60
61 end:
62 if (result != nullptr && tmp_filename != nullptr) {
63 *tmp_filename = filename_template;
64 } else {
65 gpr_free(filename_template);
66 }
67 return result;
68 }
69
70 #endif /* GPR_POSIX_TMPFILE */
71