首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

用linux系统调用杀死c++中的sh -c及其所有子进程。

在 Linux 系统中,如果你在 C++ 程序中使用 sh -c 启动了一个进程,并且希望杀死该进程及其所有子进程,可以使用以下方法:

  1. 获取进程 ID (PID):首先,你需要获取 sh -c 命令启动的进程的 PID。
  2. 获取子进程:然后,你需要获取该进程的所有子进程。
  3. 杀死进程及其子进程:最后,杀死这些进程。

以下是一个示例代码,展示了如何在 C++ 中实现这一过程:

示例代码

代码语言:javascript
复制
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <vector>
#include <cstring>
#include <sstream>
#include <fstream>

// 获取给定进程的所有子进程
std::vector<pid_t> getChildProcesses(pid_t pid) {
    std::vector<pid_t> childPids;
    std::ifstream proc("/proc/" + std::to_string(pid) + "/task/" + std::to_string(pid) + "/children");
    if (proc) {
        std::string line;
        std::getline(proc, line);
        std::istringstream iss(line);
        pid_t childPid;
        while (iss >> childPid) {
            childPids.push_back(childPid);
        }
    }
    return childPids;
}

// 递归杀死进程及其所有子进程
void killProcessTree(pid_t pid) {
    std::vector<pid_t> childPids = getChildProcesses(pid);
    for (pid_t childPid : childPids) {
        killProcessTree(childPid);
    }
    kill(pid, SIGKILL);
}

int main() {
    pid_t pid = fork();
    if (pid == 0) {
        // 子进程
        execl("/bin/sh", "sh", "-c", "sleep 100", (char *)NULL);
        // 如果 execl 失败
        std::cerr << "execl failed: " << strerror(errno) << std::endl;
        return 1;
    } else if (pid > 0) {
        // 父进程
        std::cout << "Started process with PID: " << pid << std::endl;
        sleep(5); // 等待一段时间,模拟一些操作

        // 杀死进程及其所有子进程
        killProcessTree(pid);
        std::cout << "Killed process tree with root PID: " << pid << std::endl;

        // 等待子进程结束
        waitpid(pid, NULL, 0);
    } else {
        // fork 失败
        std::cerr << "fork failed: " << strerror(errno) << std::endl;
        return 1;
    }

    return 0;
}

解释

  1. 获取子进程
    • getChildProcesses 函数读取 /proc/[pid]/task/[pid]/children 文件来获取给定进程的所有子进程。
  2. 递归杀死进程树
    • killProcessTree 函数递归地获取并杀死所有子进程,然后杀死自身。
  3. 主程序
    • 使用 fork 创建一个子进程,并使用 execl 执行 sh -c "sleep 100" 命令。
    • 父进程等待一段时间后,调用 killProcessTree 函数来杀死子进程及其所有子进程。

注意事项

  • 权限:确保你的程序有足够的权限来读取 /proc 文件系统和杀死进程。
  • 错误处理:在实际应用中,添加更多的错误处理代码是一个好习惯。
  • 信号处理:在某些情况下,你可能需要处理不同的信号(如 SIGTERM)而不是直接使用 SIGKILL
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券