0

I need to kill java process, that runs main class blabla.class. I can use function kill(pid_t, SIGKILL) for this reason, but I need to get PID ID.

I could run linux command ps-ax | grep blabla to find PID ID. What is the best way to do this using C ?

vico
  • 17,051
  • 45
  • 159
  • 315
  • 3
    You can either run `ps` in a subprocess, or troll through the per-process subdirectories of the /proc directory yourself, checking each /proc/###/cmdline against your pattern of interest. – Chris Stratton Dec 10 '13 at 15:45
  • 1
    `man pgrep`, `man pkill` – bobah Dec 10 '13 at 15:45
  • possible duplicate of [How to get the PID of a process in Linux in C](http://stackoverflow.com/questions/8166415/how-to-get-the-pid-of-a-process-in-linux-in-c) – Marco Dec 10 '13 at 15:46
  • I think this is not an exact dup of @Marco's suggestion because of the "fragment" part of the question. But you could adapt the code given there to do the `ps -ax | grep blabla` and look at the returned string. – Floris Dec 10 '13 at 16:05
  • `PID ID` is nice ... ;-) – alk Dec 10 '13 at 19:17

1 Answers1

1

Adapting the link given by Marco https://stackoverflow.com/a/8166467/1967396:

#define LEN 100
char line[LEN];
FILE *cmd = popen("ps -ax | grep blabla", "r");

fgets(line, LEN, cmd);
// now parse `line` for the information you want, using sscanf perhaps?
// I believe the pid is the first word on the line returned, and it fits in an int:
int pid;
sscanf(line, "%d", &pid);

pclose(cmd);
Community
  • 1
  • 1
Floris
  • 45,857
  • 6
  • 70
  • 122