Untitled

 avatar
unknown
plain_text
2 months ago
2.9 kB
3
Indexable
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <cstdio>
#include <cstdlib>

void monitor_cgroup_procs(const std::string &file_path) {
    // Use popen to run inotifywait and capture the output
    std::string command = "inotifywait -m -e modify --format '%e' " + file_path + " 2>/dev/null";
    FILE *pipe = popen(command.c_str(), "r");
    if (!pipe) {
        std::cerr << "Failed to run inotifywait. Make sure it's installed on the device." << std::endl;
        return;
    }

    std::cout << "Monitoring file: " << file_path << "..." << std::endl;

    std::string previous_content;

    char buffer[128];
    while (fgets(buffer, sizeof(buffer), pipe)) {
        std::string event = buffer;
        if (event.find("MODIFY") != std::string::npos) {
            std::ifstream file(file_path);
            if (!file.is_open()) {
                std::cerr << "Failed to open file: " << file_path << std::endl;
                break;
            }

            // Read the current content of the file
            std::string current_content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
            file.close();

            // Display changes
            std::cout << "File modified!" << std::endl;
            if (!previous_content.empty()) {
                std::cout << "Previous content:\n" << previous_content << std::endl;
                std::cout << "Current content:\n" << current_content << std::endl;

                // Calculate added/removed lines
                std::istringstream prev_stream(previous_content), curr_stream(current_content);
                std::string line;
                std::map<std::string, bool> prev_lines, curr_lines;

                while (std::getline(prev_stream, line)) {
                    prev_lines[line] = true;
                }
                while (std::getline(curr_stream, line)) {
                    curr_lines[line] = true;
                }

                std::cout << "Added lines:\n";
                for (const auto &entry : curr_lines) {
                    if (prev_lines.find(entry.first) == prev_lines.end()) {
                        std::cout << entry.first << std::endl;
                    }
                }

                std::cout << "Removed lines:\n";
                for (const auto &entry : prev_lines) {
                    if (curr_lines.find(entry.first) == curr_lines.end()) {
                        std::cout << entry.first << std::endl;
                    }
                }
            }

            previous_content = current_content;
        }
    }

    pclose(pipe);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        std::cerr << "Usage: " << argv[0] << " <file_path>" << std::endl;
        return 1;
    }

    std::string file_path = argv[1];
    monitor_cgroup_procs(file_path);

    return 0;
}
Leave a Comment