如何使用c++以编程方式终止进程
How to kill a process programatically using c++?
伙计们,我试图通过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()
这样的函数来获得基于该错误代码的描述性错误消息。
相关文章:
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 如何在c++中为模板函数实例创建快捷方式
- 在c代码之间共享数据的最佳方式
- 在C++中将函数压缩为两种方式
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 以螺旋方式打印矩阵的程序.(工作不好)
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 创建引用向量的优雅方式
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 不同/较旧的处理器运行c++代码的方式是否不同
- 以这种方式初始化的 char 数组是否会自动添加空终止符?
- 此应用程序已请求运行时以异常方式终止它 QT C++
- 是否有一种方法可以在输入负数时平均不包括负数,这是您终止程序的方式
- 我的Qt C++程序以一种不同寻常的方式终止
- 如何以独立于平台的方式终止挂起在阻塞 IO 上的线程
- 如何检测std::线程以异步方式终止?
- 如何使用c++以编程方式终止进程