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

前端 未结 2 856
遇见更好的自我
遇见更好的自我 2021-01-06 10:59

Some time ago I needed to write c++ code to kill some process. In my main program I run large CAE-system package with system(\"...\") with different filename strings on inpu

相关标签:
2条回答
  • 2021-01-06 11:38

    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());
    
    0 讨论(0)
  • 2021-01-06 11: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.

    0 讨论(0)
提交回复
热议问题