如何使用c++以编程方式终止进程

How to kill a process programatically using c++?

本文关键字:方式 终止 进程 编程 何使用 c++      更新时间:2023-10-16

伙计们,我试图通过c++程序杀死进程,它正在杀死进程,但在杀死进程后没有得到所需的输出,我想要的输出是在杀死if块中的进程后显示剩余的运行进程,而不是显示else块。我交换了这个块& &;Else块也没有得到想要的输出。下面是代码:

#include<iostream>
#include<cstdlib>
#include<csignal>
using namespace std;
int main()
{   
    int pid,f=0;
    system("ps -all");
    cout<<"Enter the Process ID to killn";
    cin>>pid;
    if((kill(pid,SIGKILL))){
        f=1;
    }
    if(f)
    {
        cout<<"List of processes after killing the process with PID"<<pid<<"are"<<"n";
        system("ps -l");
    }
    else    
    {   
        cout<<"Cant kill the processn";
    }   
    return 0;
}

您需要切换if/else情况:kill()成功时返回0,失败时返回-1。只有当f=1失败时才设置它。

同样,当它失败时,它将errno设置为提供失败原因的错误代码。您可以使用像perror()strerror()这样的函数来获得基于该错误代码的描述性错误消息。