Ch 10: 系统与进程
- 处理文件系统操作
- 调用外部进程
- 管理环境变量
- 理解线程基础
10.1 Python os 模块
Section titled “10.1 Python os 模块”os 模块提供操作系统交互接口:
import os
# 环境变量home = os.environ["HOME"]path = os.getenv("PATH", "")os.putenv("VAR", "value")
# 命令行参数import syssys.argv # [程序名, arg1, arg2, ...]
# 目录操作os.getcwd() # 当前目录os.chdir("/tmp") # 切换目录os.mkdir("dir") # 创建目录os.makedirs("a/b/c") # 递归创建os.rmdir("dir") # 删除空目录os.remove("file.txt") # 删除文件os.rename("old", "new") # 重命名
# 文件信息os.path.exists("file.txt")os.path.isfile("file.txt")os.path.isdir("path")os.path.getsize("file.txt")os.path.join("dir", "file.txt")os.path.split("/a/b.txt") # ('/a', 'b.txt')
# 目录内容os.listdir(".")os.scandir(".") # 更高效的迭代器
# 文件权限os.chmod("file.txt", 0o755)os.access("file.txt", os.R_OK | os.W_OK)10.2 C++ 文件系统和环境
Section titled “10.2 C++ 文件系统和环境”#include <filesystem>#include <cstdlib>#include <iostream>
namespace fs = std::filesystem;
// 环境变量const char* home = std::getenv("HOME");const char* path = std::getenv("PATH");std::setenv("VAR", "value", 1); // 1 = overwrite
// main 函数参数int main(int argc, char* argv[]) { for (int i = 0; i < argc; ++i) { std::cout << argv[i] << std::endl; }}
// 目录操作fs::current_path(); // 当前目录fs::current_path(fs::path("/tmp")); // 切换fs::create_directory("dir"); // 创建目录fs::create_directories("a/b/c"); // 递归创建fs::remove("dir"); // 删除空目录fs::remove("file.txt"); // 删除文件fs::rename("old", "new"); // 重命名
// 文件信息fs::exists("file.txt");fs::is_regular_file("file.txt");fs::is_directory("path");fs::file_size("file.txt");fs::path p = "dir" / "file.txt"; // 路径拼接
// 目录内容for (const auto& entry : fs::directory_iterator(".")) { std::cout << entry.path() << std::endl;}
// 文件权限(C++20)fs::permissions("file.txt", fs::perms::owner_read | fs::perms::owner_write);10.3 Python subprocess
Section titled “10.3 Python subprocess”subprocess 用于执行外部命令:
import subprocess
# 执行命令(等待完成)result = subprocess.run( ["ls", "-la"], capture_output=True, # 捕获输出 text=True # 返回字符串)print(result.stdout)print(result.stderr)print(result.returncode) # 退出码
# 检查返回码if result.returncode != 0: print(f"Error: {result.stderr}")
# shell=True(注意安全)result = subprocess.run("ls -la | grep txt", shell=True)
# 捕获输出但不等待proc = subprocess.Popen( ["python", "script.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)stdout, stderr = proc.communicate()
# 发送信号proc.terminate() # SIGTERMproc.kill() # SIGKILL
# 超时result = subprocess.run( ["sleep", "10"], timeout=5 # 5 秒超时)10.4 C++ 进程操作
Section titled “10.4 C++ 进程操作”std::system
Section titled “std::system”#include <cstdlib>#include <iostream>
int main() { // 简单调用 int result = std::system("ls -la");
// 检查返回码 if (result != 0) { std::cerr << "Command failed" << std::endl; }
return 0;}C++20 std::process
Section titled “C++20 std::process”C++20 引入了 std::process:
#include <processes>#include <iostream>
int main() { // 运行命令 auto result = std::process::system("ls -la");
// 异步执行(C++20) auto child = std::process::spawn("python", {"script.py"});
// 等待完成 auto exit_status = child.wait(); std::cout << "Exit code: " << exit_status << std::endl;
// 注意:std::process 是 C++20 标准库扩展 // 很多编译器尚未完全支持
return 0;}popen/pclose(POSIX)
Section titled “popen/pclose(POSIX)”#include <cstdio>#include <iostream>
int main() { // 读取命令输出 FILE* fp = std::popen("ls -la", "r"); if (fp) { char buf[256]; while (std::fgets(buf, sizeof(buf), fp) != nullptr) { std::cout << buf; } std::pclose(fp); }
return 0;}10.5 Python threading
Section titled “10.5 Python threading”import threading
# 创建线程def worker(n): print(f"Thread {n} started")
t = threading.Thread(target=worker, args=(1,))t.start()t.join()
# 带返回值def worker_with_return(n): return n * 2
with concurrent.futures.ThreadPoolExecutor() as executor: future = executor.submit(worker_with_return, 5) result = future.result() # 10
# 锁lock = threading.Lock()with lock: # 临界区 pass
# 事件event = threading.Event()event.wait() # 等待event.set() # 设置event.clear() # 清除
# 条件变量cv = threading.Condition()cv.wait()cv.notify()cv.notify_all()
# 队列from queue import Queueq = Queue()q.put(1)q.get()10.6 C++ std::thread
Section titled “10.6 C++ std::thread”#include <thread>#include <mutex>#include <condition_variable>#include <queue>#include <iostream>
void worker(int n) { std::cout << "Thread " << n << " started" << std::endl;}
int main() { // 创建线程 std::thread t1(worker, 1); std::thread t2(worker, 2);
t1.join(); t2.join();
// Lambda 线程 std::thread t3([](int x) { std::cout << x * 2 << std::endl; }, 5); t3.join();
return 0;}#include <mutex>
std::mutex mtx;
void safe_increment() { std::lock_guard<std::mutex> lock(mtx); // RAII 锁 // 临界区 counter++;} // 锁自动释放
// 或手动mtx.lock();counter++;mtx.unlock();
// unique_lock - 更灵活std::unique_lock<std::mutex> lock(mtx, std::defer_lock);// ... 做其他事 ...lock.lock();// ... 临界区 ...#include <condition_variable>#include <mutex>#include <queue>
std::mutex mtx;std::condition_variable cv;std::queue<int> q;
void producer() { for (int i = 0; i < 10; ++i) { { std::lock_guard<std::mutex> lock(mtx); q.push(i); } cv.notify_one(); }}
void consumer() { while (true) { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [] { return !q.empty() || done; }); if (q.empty()) break; int val = q.front(); q.pop(); lock.unlock(); // 处理 val }}future 和 async
Section titled “future 和 async”#include <future>#include <iostream>
int async_task(int x) { return x * 2;}
int main() { // 异步执行 std::future<int> f = std::async(std::launch::async, async_task, 42); int result = f.get(); // 阻塞直到完成
std::cout << result << std::endl;
return 0;}10.7 线程 vs 进程
Section titled “10.7 线程 vs 进程”| 维度 | 线程 | 进程 |
|---|---|---|
| 内存共享 | 共享内存 | 独立内存 |
| 创建开销 | 小 | 大 |
| 通信 | 简单(共享内存) | 复杂(IPC) |
| 稳定性 | 一个线程崩溃可能影响其他 | 更隔离 |
| Python GIL | 受限 | 不受影响 |
Python GIL:
import threadingimport time
# CPU 密集型 - GIL 限制def cpu_task(): while True: x = 1 + 2
t1 = threading.Thread(target=cpu_task)t2 = threading.Thread(target=cpu_task)t1.start()t2.start()# 两个线程不能真正并行执行!C++ 无 GIL:
#include <thread>#include <vector>
void cpu_task() { volatile long x = 0; for (long i = 0; i < 1e9; ++i) { x += 1; }}
int main() { std::vector<std::thread> threads; for (int i = 0; i < 4; ++i) { threads.emplace_back(cpu_task); } for (auto& t : threads) { t.join(); } // 真正并行执行! return 0;}std::filesystem处理文件和目录std::getenv/std::setenv处理环境变量- C++20
std::process提供进程管理 std::thread和std::mutex处理线程
下章预告:ch11 错误处理与异常。