How to kill process in c++, knowing only part of its name

我只是一个虾纸丫 提交于 2019-11-30 22:42:44

You don't have to open a shell to kill a process. Just use the "kill" function:

#include <sys/types.h>
#include <signal.h>

int kill(pid_t pid, int sig);

http://linux.die.net/man/2/kill

To find a process to kill read the following directory:

/proc/####/cmdline

Where #### is the number of any running process id. So the code roughly would be to read the /proc directory and list out all the numerical directories, these are the current running processes, and you find the name of the command that spawned that process in the "cmdline" file in that directory. You can then use a regular expression, or a string comparison to identify processes to kill.

This should just work assuming filename isn't too much exotic or contains a regular expression pattern:

string s="pkill -9 -f "+filename";
system(s.c_str());

As a side note, -9 is a last resort signal, not something you should start with. I would thus recommend the less brutal:

string s="pkill -f "+filename"+";sleep 2; pkill -9 -f "+filename;
system(s.c_str());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!