c++写一个查询工作站服务器中每个用户的空间使用量

工作中有一个小需求,需要统计用户空间使用量

统计空间的主函数:

#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <string>
#include <cstdlib>
#include <sys/types.h>
#include <pwd.h>
#include <unistd.h>
#include <vector>
#include <cstring>
#include <thread>
#include <mutex>// 获取所有用户的home目录
std::vector<std::string> getUsersHomeDirectories() {std::vector<std::string> homeDirs;struct passwd *pw;while ((pw = getpwent()) != NULL) {if (pw->pw_dir) {homeDirs.push_back(pw->pw_dir);}}endpwent();return homeDirs;
}// 运行系统命令并获取输出
std::string exec(const char* cmd) {std::array<char, 128> buffer;std::string result;std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);if (!pipe) throw std::runtime_error("popen() failed!");while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {result += buffer.data();}return result;
}// 获取单个用户目录的磁盘使用量
void getDiskUsage(const std::string& dir, std::map<std::string, long>& usage, std::mutex& mtx) {std::string cmd = "du -sb " + dir + " | cut -f1";std::string output = exec(cmd.c_str());long size = std::stol(output);std::lock_guard<std::mutex> lock(mtx);usage[dir] = size;
}int main() {std::vector<std::string> homeDirs = getUsersHomeDirectories();std::map<std::string, long> usage;std::mutex mtx;std::vector<std::thread> threads;for (const auto& dir : homeDirs) {threads.emplace_back(getDiskUsage, std::ref(dir), std::ref(usage), std::ref(mtx));}for (auto& th : threads) {if (th.joinable()) {th.join();}}std::cout << "User Directory Disk Usage:\n";for (const auto& pair : usage) {std::cout << pair.first << ": " << pair.second << " bytes\n";}return 0;
}

可重复使用线程的线程池:

#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>class ThreadPool {
public:ThreadPool(size_t threads);~ThreadPool();template<class F, class... Args>auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>;private:// 工作线程函数void worker();// 线程池中的线程std::vector<std::thread> workers;// 任务队列std::queue<std::function<void()>> tasks;// 同步std::mutex queue_mutex;std::condition_variable condition;bool stop;
};ThreadPool::ThreadPool(size_t threads): stop(false) {for(size_t i = 0; i < threads; ++i) {workers.emplace_back([this] { this->worker(); });}
}ThreadPool::~ThreadPool() {{std::unique_lock<std::mutex> lock(queue_mutex);stop = true;}condition.notify_all();for(std::thread &worker: workers) {worker.join();}
}void ThreadPool::worker() {while(true) {std::function<void()> task;{std::unique_lock<std::mutex> lock(this->queue_mutex);this->condition.wait(lock, [this]{ return this->stop || !this->tasks.empty(); });if(this->stop && this->tasks.empty()) {return;}task = std::move(this->tasks.front());this->tasks.pop();}task();}
}template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> {using return_type = typename std::result_of<F(Args...)>::type;auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));std::future<return_type> res = task->get_future();{std::unique_lock<std::mutex> lock(queue_mutex);// don't allow enqueueing after stopping the poolif(stop) {throw std::runtime_error("enqueue on stopped ThreadPool");}tasks.emplace([task](){ (*task)(); });}condition.notify_one();return res;
}

测试点:

#include <iostream>
#include <chrono>int main() {ThreadPool pool(4);auto result1 = pool.enqueue([](int answer) {std::this_thread::sleep_for(std::chrono::seconds(1));return answer;}, 42);auto result2 = pool.enqueue([](int answer) {std::this_thread::sleep_for(std::chrono::seconds(2));return answer;}, 24);std::cout << "Result 1: " << result1.get() << std::endl;std::cout << "Result 2: " << result2.get() << std::endl;return 0;
}

两者的结合:

#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <sys/types.h>
#include <pwd.h>
#include <unistd.h>
#include <mutex>
#include <thread>
#include <functional>
#include <future>// 线程池类的实现(与前面的实现相同)
// ...(省略前面的ThreadPool类实现)// 获取所有用户的home目录
std::vector<std::string> getUsersHomeDirectories() {std::vector<std::string> homeDirs;struct passwd *pw;while ((pw = getpwent()) != NULL) {if (pw->pw_dir) {homeDirs.push_back(pw->pw_dir);}}endpwent();return homeDirs;
}// 运行系统命令并获取输出
std::string exec(const char* cmd) {std::array<char, 128> buffer;std::string result;std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);if (!pipe) throw std::runtime_error("popen() failed!");while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {result += buffer.data();}return result;
}// 获取单个用户目录的磁盘使用量
long getDiskUsage(const std::string& dir) {std::string cmd = "du -sb " + dir + " | cut -f1";std::string output = exec(cmd.c_str());return std::stol(output);
}int main() {std::vector<std::string> homeDirs = getUsersHomeDirectories();std::map<std::string, long> usage;std::mutex mtx;ThreadPool pool(8);std::vector<std::future<long>> results;for (const auto& dir : homeDirs) {results.emplace_back(pool.enqueue([&dir]() {return getDiskUsage(dir);}));}for (size_t i = 0; i < homeDirs.size(); ++i) {usage[homeDirs[i]] = results[i].get();}std::cout << "User Directory Disk Usage:\n";for (const auto& pair : usage) {std::cout << pair.first << ": " << pair.second << " bytes\n";}return 0;
}

自己实现发送email的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>class EmailSender {
public:bool sendEmail(const std::string& to, const std::string& from, const std::string& subject, const std::string& html_content) {std::string emailContent = "To: " + to + "\n" +"From: " + from + "\n" +"Subject: " + subject + "\n" +"Content-Type: text/html; charset=UTF-8\n\n" +html_content;// 将邮件内容写入临时文件std::string tempFileName = "/tmp/email.txt";std::ofstream emailFile(tempFileName);if (!emailFile.is_open()) {std::cerr << "Failed to create temporary email file." << std::endl;return false;}emailFile << emailContent;emailFile.close();// 使用系统命令发送邮件std::string command = "sendmail -t < " + tempFileName;int result = std::system(command.c_str());// 删除临时文件std::remove(tempFileName.c_str());return result == 0;}
};int main() {EmailSender emailSender;std::string to = "recipient@example.com";std::string from = "sender@example.com";std::string subject = "Test Email";std::string html_content = "<html><body><h1>Hello, World!</h1></body></html>";if (emailSender.sendEmail(to, from, subject, html_content)) {std::cout << "Email sent successfully!" << std::endl;} else {std::cout << "Failed to send email." << std::endl;}return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/872807.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

LabVIEW 与 PLC 通讯方式

在工业自动化中&#xff0c;LabVIEW 与 PLC&#xff08;可编程逻辑控制器&#xff09;的通信至关重要&#xff0c;常见的通信方式包括 OPC、Modbus、EtherNet/IP、Profibus/Profinet 和 Serial&#xff08;RS232/RS485&#xff09;。这些通信协议各有特点和应用场景&#xff0c…

从零手写实现 nginx-31-load balance 负载均衡介绍

前言 大家好&#xff0c;我是老马。很高兴遇到你。 我们为 java 开发者实现了 java 版本的 nginx https://github.com/houbb/nginx4j 如果你想知道 servlet 如何处理的&#xff0c;可以参考我的另一个项目&#xff1a; 手写从零实现简易版 tomcat minicat 手写 nginx 系列 …

@google/model-viewer 导入 改纹理 (http-serve)

导入模型 改纹理 效果图 <template><div><h1>鞋模型</h1><model-viewerstyle"width: 300px; height: 300px"id"my-replace-people"src"/imgApi/Astronaut.glb"auto-rotatecamera-controls></model-viewer>&…

C++STL---priority_queue知识总结及模拟实现

前言 和stack与queue一样&#xff0c;priority_queue也是一种容器适配器。 他的本质其实是堆&#xff0c;作优先级队列的底层需要能够通过随机迭代器访问&#xff0c;所以他的底层是可以由vector和queue实例化&#xff0c;默认情况下priority_queue默认是用vector作为底层实例…

智慧博物馆的“眼睛”:视频智能监控技术守护文物安全与智能化管理

近日&#xff0c;位于四川德阳的三星堆博物馆迎来了参观热潮。据新闻报道&#xff0c;三星堆博物馆的日均参观量达1.5万人次。随着暑假旅游高峰期的到来&#xff0c;博物馆作为重要的文化场所&#xff0c;也迎来了大量游客。博物馆作为文化和历史的重要载体&#xff0c;其安全保…

关于vue实现导出excel表,以及导出的excel后的图片超过单元格的问题

实现导出带图标片的excel的方法&#xff0c; 首先&#xff1a; import table2excel from js-table2excel // 导出表格 按钮点击后触发事件 const onBatchExport () > {const column [//数据表单{title: "ID", //表头名称titlekey: "id", //数据ty…

通用图形处理器设计GPGPU基础与架构(四)

一、前言 本文将介绍GPGPU中线程束的调度方案、记分牌方案和线程块的分配与调度方案。 二、线程束调度 在计算机中有很多资源&#xff0c;既可以是虚拟的计算资源&#xff0c;如线程、进程或数据流&#xff0c;也可以是硬件资源&#xff0c;如处理器、网络连接或 ALU 单元。调…

Visual Studio2022中使用.Net 8 在 Windows 下使用 Worker Service 创建守护进程

Visual Studio2022中使用.Net 8 在 Windows 下创建 Worker Service 1 什么是 .NET Core Worker Service1.1 确认Visual Studio中安装了 ASP.NET和Web开发2 创建 WorkerService项目2.1 新建一个WorkerService项目2.2 项目结构说明3 将应用转换成 Windows 服务3.1 安装Microsoft.…

前端书籍翻页效果

目录 前端书籍翻页效果前言代码示例创建模板页面css样式编写js代码 结论 前端书籍翻页效果 前端实现翻书效果&#xff0c;附带vue源码 源码下载地址 前言 实际业务开发中&#xff0c;有时候会遇到需要在前端页面内实现翻书效果的需求&#xff0c;本篇文章就为大家介绍如何使…

09 深度推荐模型演化中的“平衡与不平衡“规律

你好&#xff0c;我是大壮。08 讲我们介绍了深度推荐算法中的范式方法&#xff0c;并简单讲解了组合范式推荐方法&#xff0c;其中还提到了多层感知器&#xff08;MLP&#xff09;。因此&#xff0c;这一讲我们就以 MLP 组件为基础&#xff0c;讲解深度学习范式的其他组合推荐方…

电子设备中丝杆模组高精度重复定位技术的原理!

丝杆模组是由螺旋丝杆和导杆组成的一种机械运动控制系统&#xff0c;通过在导杆内进行旋转&#xff0c;使导杆沿着线性方向进行移动&#xff0c;从而实现机械运动的线性控制。丝杆模组以其高精度、高稳定性和可重复定位的特性&#xff0c;在现代工业自动化和精密制造领域发挥着…

controller-from表单1

mvc模式是spring boot 开发web应用程序主要使用模式&#xff0c;mvc分别代表model模型&#xff0c;view是视图 &#xff0c;controller是控制器 controller是对接用户请求数据调用服务层代码&#xff0c;具体怎么操作 浏览器发送http请求给到dispatcherServlet&#xff08;前…

c++ primer plus 第16章string 类和标准模板库,string 类输入

c primer plus 第16章string 类和标准模板库,string 类输入 c primer plus 第16章string 类和标准模板库,string 类输入 文章目录 c primer plus 第16章string 类和标准模板库,string 类输入16.1.2 string 类输入程序清单 16.2 strfile.cpp 16.1.2 string 类输入 对于类&…

【操作系统】文件管理——文件存储空间管理(个人笔记)

学习日期&#xff1a;2024.7.17 内容摘要&#xff1a;文件存储空间管理、文件的基本操作 在上一章中&#xff0c;我们学习了文件物理结构的管理&#xff0c;重点学习了操作系统是如何实现逻辑结构到物理结构的映射&#xff0c;这显然是针对已经存储了文件的磁盘块的&#xff0…

题解|2023暑期杭电多校03

【原文链接】 &#xff08;补发&#xff09;题解|2023暑期杭电多校03 1011.8-bit Zoom 不那么签到的签到题、模拟题 题目大意 给定一个 n n n\times n nn 大小的字符矩阵表示一张图片&#xff0c;每种字符代表一种颜色&#xff1b;并给定 Z Z Z 代表缩放倍率 满足以下条…

无人驾驶的未来:AI如何重塑我们的出行世界

无人驾驶汽车&#xff0c;作为人工智能&#xff08;AI&#xff09;技术的集大成者&#xff0c;正以前所未有的速度改变着我们的出行方式。从机器学习到计算机视觉&#xff0c;再到人工智能生成内容&#xff08;AIGC&#xff09;&#xff0c;AI技术的每一次进步都在为无人驾驶汽…

Linux内核编程(八) 添加自定义目录驱动菜单 (Kconfig文件使用)

本文目录 一、Linux 内核驱动目录二、自定义驱动的Kconfig编写●示例&#xff1a;在 drivers 菜单添加一个自己驱动的子菜单。 三、自写驱动的Makefile编写四、总结 一个Linux内核源码&#xff0c;其中包含了很多驱动程序&#xff0c;对应不同的功能。我们在编译内核时。如果将…

设计模式:真正的建造者模式

又臭又长的set方法 经常进行Java项目开发使用各类starter的你一定见过这种代码&#xff1a; public class SwaggerConfig {Beanpublic Docket api() {return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.any…

【BUG】已解决:ModuleNotFoundError: No module named ‘cv2’

已解决&#xff1a;ModuleNotFoundError: No module named ‘cv2’ 欢迎来到英杰社区https://bbs.csdn.net/topics/617804998 欢迎来到我的主页&#xff0c;我是博主英杰&#xff0c;211科班出身&#xff0c;就职于医疗科技公司&#xff0c;热衷分享知识&#xff0c;武汉城市开…

【Pyhton】Pip换源(Windows)

在Python中使用pip换源的方法可以通过修改pip配置文件来实现。具体步骤如下&#xff1a; 暂时修改&#xff08;只应用于本次下载&#xff09; pip install 库名 -i 国内源链接/simple --trusted-host 国内源链接 常见的国内源链接见下方永久修改中的内容。 示例&#xff1a…