1

In short, I'm trying to kill a process in the middle of its run. For example, I have a binary file test which runs something similar like:

while (true) {
  // Do something
}

I'm calling this binary file via the system() function in C++ like so:

const char* cmd = "test";
system(cmd);

Now is there any way for me to kill the process without having to manually go into the Linux shell? I have been able to manually simulate this function by running testand then typing ctrl+c into the shell. Thanks in advance :)

jww
  • 97,681
  • 90
  • 411
  • 885
Andy Jin
  • 35
  • 2
  • 2
    You can call the `kill` API direct rather than using the shell built-in. `man 2 kill`. Run the process using `fork`/`exec` rather that `system()` and you get back its `PID`. – cdarke Jul 23 '18 at 16:16
  • 1
    By the way, bad idea to call the binary `test` since that s the name of a system supplied binary and also the name of a standard shell built-in. – cdarke Jul 23 '18 at 16:18
  • Try to avoid `system()` - too little control, too many potential security problems. Prefer the `exec` family of functions if you *have* to use something so low-level. Better would be `QProcess` or some similar high level object. – Jesper Juhl Jul 23 '18 at 16:19
  • Thanks for the quick reply! The 'kill' API requires for me to know the pid so how would I be able to get that information without the shell? – Andy Jin Jul 23 '18 at 16:21
  • `getpid`, `getppid` etc. – Jesper Juhl Jul 23 '18 at 16:21
  • @AndyJin: I added an edit to my comment to use `fork`/`exec`, enter that into a search engine and you will find lots of examples. But don't call your program `test` ! – cdarke Jul 23 '18 at 16:22
  • **Why** do you want to kill it? Must it only run for a given time? If so, start it with `timeout`. You could change the program so that it checks if a file called `STOP` exists on every iteration and if it exists, it deletes the file and exits - then the calling process, or you in the Terminal, can `touch/create STOP` and it'll exit. – Mark Setchell Jul 23 '18 at 16:35
  • 1
    Read this: https://stackoverflow.com/questions/30233134/is-it-possible-a-kill-a-command-launched-using-system-api-in-c-if-not-any-alter – Fausto Carvalho Marques Silva Jul 23 '18 at 17:22
  • 2
    Possible duplicate of [Is it possible a kill a command launched using system api in C? If not any alternatives?](https://stackoverflow.com/questions/30233134/is-it-possible-a-kill-a-command-launched-using-system-api-in-c-if-not-any-alter) – Fausto Carvalho Marques Silva Jul 23 '18 at 17:23

0 Answers0