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 <errno.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27
28 #include <grpc/support/alloc.h>
29 #include <grpc/support/log.h>
30 #include <grpc/support/string_util.h>
31
32 #include "src/core/lib/gpr/string.h"
33 #include "src/core/lib/gpr/tmpfile.h"
34 #include "src/core/lib/gprpp/crash.h"
35 #include "src/core/lib/gprpp/strerror.h"
36
gpr_tmpfile(const char * prefix,char ** tmp_filename)37 FILE* gpr_tmpfile(const char* prefix, char** tmp_filename) {
38 FILE* result = nullptr;
39 char* filename_template;
40 int fd;
41
42 if (tmp_filename != nullptr) *tmp_filename = nullptr;
43
44 gpr_asprintf(&filename_template, "/tmp/%s_XXXXXX", prefix);
45 GPR_ASSERT(filename_template != nullptr);
46
47 fd = mkstemp(filename_template);
48 if (fd == -1) {
49 gpr_log(GPR_ERROR, "mkstemp failed for filename_template %s with error %s.",
50 filename_template, grpc_core::StrError(errno).c_str());
51 goto end;
52 }
53 result = fdopen(fd, "w+");
54 if (result == nullptr) {
55 gpr_log(GPR_ERROR, "Could not open file %s from fd %d (error = %s).",
56 filename_template, fd, grpc_core::StrError(errno).c_str());
57 unlink(filename_template);
58 close(fd);
59 goto end;
60 }
61
62 end:
63 if (result != nullptr && tmp_filename != nullptr) {
64 *tmp_filename = filename_template;
65 } else {
66 gpr_free(filename_template);
67 }
68 return result;
69 }
70
71 #endif // GPR_POSIX_TMPFILE
72