简体   繁体   English

如何使用C ++以编程方式杀死进程?

[英]How to kill a process programatically using c++?

Guys i am trying to kill the process through the C++ program , it's killing the process, but not getting the desired output after killing the process, my desired output is to display the remaining running processes after killing the process which is in if block ,instead of that it is displaying the else block. 伙计们,我正在尝试通过C ++程序终止该进程,这正在终止该进程,但是在终止该进程后未获得所需的输出,我想要的输出是在终止该进程后显示剩余的正在运行的进程(如果在if块中,而是其中,它显示else块。 I inter changed if block & else block too still not getting the desired output. 如果阻止和其他阻止仍然无法获得所需的输出,我会进行更改。 Here is the code: 这是代码:

#include<iostream>
#include<cstdlib>
#include<csignal>
using namespace std;
int main()
{   
    int pid,f=0;
    system("ps -all");
    cout<<"Enter the Process ID to kill\n";
    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 process\n";
    }   
    return 0;
}

You need to switch your if/else cases: kill() returns 0 when it succeeds, and -1 when it fails. 您需要切换if / else情况: kill()成功时返回0,失败时返回-1。 You're setting f=1 only when it fails. 仅在失败时才设置f=1

Also, when it fails, it sets errno to an error code that provides a reason for the failure. 另外,当失败时,它将errno为提供失败原因的错误代码。 You can use a function like perror() or strerror() to get a descriptive error message based on that error code. 您可以使用类似perror()strerror()的函数来获取基于该错误代码的描述性错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM