1 /* 2 * Copyright (C) 2023 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 <sys/inotify.h> 18 #include <unistd.h> 19 #include <string> 20 #include <vector> 21 22 #include <android-base/logging.h> 23 24 namespace cuttlefish { 25 26 #define INOTIFY_MAX_EVENT_SIZE (sizeof(struct inotify_event) + NAME_MAX + 1) GetCreatedFileListFromInotifyFd(int fd)27std::vector<std::string> GetCreatedFileListFromInotifyFd(int fd) { 28 char event_readout[INOTIFY_MAX_EVENT_SIZE]; 29 int bytes_parsed = 0; 30 std::vector<std::string> result; 31 // Each successful read can contain one or more of inotify_event events 32 // Note: read() on inotify returns 'whole' events, will never partially 33 // populate the buffer. 34 int event_read_out_length = read(fd, event_readout, INOTIFY_MAX_EVENT_SIZE); 35 36 if (event_read_out_length == -1) { 37 LOG(ERROR) << __FUNCTION__ 38 << ": Couldn't read out inotify event due to error: '" 39 << strerror(errno) << "' (" << errno << ")"; 40 return std::vector<std::string>(); 41 } 42 43 while (bytes_parsed < event_read_out_length) { 44 struct inotify_event* event = 45 reinterpret_cast<inotify_event*>(event_readout + bytes_parsed); 46 bytes_parsed += sizeof(struct inotify_event) + event->len; 47 48 // No file name was present 49 if (event->len == 0) { 50 LOG(ERROR) << __FUNCTION__ << ": inotify event didn't contain filename"; 51 continue; 52 } 53 if (!(event->mask & IN_CREATE)) { 54 LOG(ERROR) << __FUNCTION__ 55 << ": inotify event didn't pertain to file creation"; 56 continue; 57 } 58 result.push_back(std::string(event->name)); 59 } 60 61 return result; 62 } 63 64 } // namespace cuttlefish 65