Elliott Hughes | b4f7616 | 2013-09-19 16:27:24 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2013 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include <unistd.h> |
| 18 | |
Calin Juravle | fe317a3 | 2014-02-21 15:11:03 +0000 | [diff] [blame^] | 19 | template<int (*mk_func)(char*)> |
| 20 | class GenericTemporaryFile { |
Elliott Hughes | b4f7616 | 2013-09-19 16:27:24 -0700 | [diff] [blame] | 21 | public: |
Calin Juravle | fe317a3 | 2014-02-21 15:11:03 +0000 | [diff] [blame^] | 22 | GenericTemporaryFile() { |
Elliott Hughes | 925753a | 2013-10-18 13:17:18 -0700 | [diff] [blame] | 23 | // Since we might be running on the host or the target, and if we're |
| 24 | // running on the host we might be running under bionic or glibc, |
| 25 | // let's just try both possible temporary directories and take the |
| 26 | // first one that works. |
| 27 | init("/data/local/tmp"); |
| 28 | if (fd == -1) { |
| 29 | init("/tmp"); |
| 30 | } |
Elliott Hughes | b4f7616 | 2013-09-19 16:27:24 -0700 | [diff] [blame] | 31 | } |
| 32 | |
Calin Juravle | fe317a3 | 2014-02-21 15:11:03 +0000 | [diff] [blame^] | 33 | ~GenericTemporaryFile() { |
Elliott Hughes | b4f7616 | 2013-09-19 16:27:24 -0700 | [diff] [blame] | 34 | close(fd); |
| 35 | unlink(filename); |
| 36 | } |
| 37 | |
| 38 | int fd; |
| 39 | char filename[1024]; |
Elliott Hughes | 925753a | 2013-10-18 13:17:18 -0700 | [diff] [blame] | 40 | |
| 41 | private: |
| 42 | void init(const char* tmp_dir) { |
| 43 | snprintf(filename, sizeof(filename), "%s/TemporaryFile-XXXXXX", tmp_dir); |
Calin Juravle | fe317a3 | 2014-02-21 15:11:03 +0000 | [diff] [blame^] | 44 | fd = mk_func(filename); |
Elliott Hughes | 925753a | 2013-10-18 13:17:18 -0700 | [diff] [blame] | 45 | } |
Elliott Hughes | b4f7616 | 2013-09-19 16:27:24 -0700 | [diff] [blame] | 46 | }; |
Calin Juravle | fe317a3 | 2014-02-21 15:11:03 +0000 | [diff] [blame^] | 47 | |
| 48 | typedef GenericTemporaryFile<mkstemp> TemporaryFile; |