gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:48:06 25 4
gpt4 key购买 nike

伙计们,我试图通过 C++ 程序杀死进程,它正在杀死进程,但在杀死进程后没有得到所需的输出,我所需的输出是在杀死 if block 中的进程后显示剩余的正在运行的进程,而不是显示 else block 。我也更改了 if block 和 else block ,但仍然没有得到所需的输出。这是代码:

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

最佳答案

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

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

关于c++ - 如何使用 C++ 以编程方式终止进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22650033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com