• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <grpc/support/alloc.h>
25 #include <grpc/support/string_util.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 
30 #include "absl/log/check.h"
31 #include "absl/log/log.h"
32 #include "src/core/util/crash.h"
33 #include "src/core/util/strerror.h"
34 #include "src/core/util/string.h"
35 #include "src/core/util/tmpfile.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   CHECK_NE(filename_template, nullptr);
46 
47   fd = mkstemp(filename_template);
48   if (fd == -1) {
49     LOG(ERROR) << "mkstemp failed for filename_template " << filename_template
50                << " with error " << grpc_core::StrError(errno);
51     goto end;
52   }
53   result = fdopen(fd, "w+");
54   if (result == nullptr) {
55     LOG(ERROR) << "Could not open file " << filename_template << " from fd "
56                << fd << " (error = " << grpc_core::StrError(errno) << ").";
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