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

   2024-09-30 6340
核心提示:在C++中,你可以使用std::system()函数或者直接使用POSIX的fork()和exec()函数来结合其他系统调用来使用kill方法1:使用std::sys

在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用户身份运行程序。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号