温馨提示×

C++中如何结合其他系统调用来使用kill

c++
小樊
81
2024-09-11 18:15:09
栏目: 编程语言

在C++中,你可以使用std::system()函数或者直接使用POSIX的fork()exec()函数来结合其他系统调用来使用kill

方法1:使用std::system()函数

#include<iostream>
#include <cstdlib>

int main() {
    int pid = 0; // 这里填写你要杀死的进程的PID
    std::string cmd = "kill -9 " + std::to_string(pid);
    int result = std::system(cmd.c_str());

    if (result == 0) {
        std::cout << "成功杀死进程"<< std::endl;
    } else {
        std::cerr << "无法杀死进程"<< std::endl;
    }

    return 0;
}

方法2:使用fork()exec()函数

#include<iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <cstdlib>

int main() {
    int pid = 0; // 这里填写你要杀死的进程的PID
    pid_t child_pid = fork();

    if (child_pid == 0) {
        // 子进程
        char *args[] = {"kill", "-9", std::to_string(pid).c_str(), nullptr};
        execvp("kill", args);
    } else if (child_pid > 0) {
        // 父进程
        int status;
        waitpid(child_pid, &status, 0);

        if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
            std::cout << "成功杀死进程"<< std::endl;
        } else {
            std::cerr << "无法杀死进程"<< std::endl;
        }
    } else {
        std::cerr << "fork失败"<< std::endl;
    }

    return 0;
}

请注意,这些示例需要你有适当的权限来杀死目标进程。如果你没有足够的权限,你可能需要以root用户身份运行程序。

0