溫馨提示×

C++中如何結合其他系統(tǒng)調用來使用kill

c++
小樊
81
2024-09-11 18:15:09
欄目: 編程語言

在C++中,你可以使用std::system()函數(shù)或者直接使用POSIX的fork()exec()函數(shù)來結合其他系統(tǒng)調用來使用kill

方法1:使用std::system()函數(shù)

#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()函數(shù)

#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;
}

請注意,這些示例需要你有適當?shù)臋嘞迊須⑺滥繕诉M程。如果你沒有足夠的權限,你可能需要以root用戶身份運行程序。

0