chmoelders
chmoelders

Reputation: 18674

Get PID by parsing the output of /bin/ps

Within a C-program I'm reading line by line the output of /bin/ps -fu1000 and searching for a string, for example "gnome". When I found the string (gnome), how can I get the pid? The whole line is saved in a char buf[256].

cm       12556     1  0 10:47 ?        00:00:13 gnome-terminal

... and yes it's part of a homework.


After reading some comments:

I had to use C. Goal of the task is to write a program which will send signals to running processes, containing a specified string in its name.

My approach is like:

fp = popen("/bin/ps -fu1000", "r");
while(fgets(line, sizeof line, fp)){
  if(strstr(line, "gnome")){
    printf("found\n");
    /* do some nice stuff to get the PID */
  }
}

Upvotes: 1

Views: 1435

Answers (3)

mripard
mripard

Reputation: 2356

If you are on a Linux platform, with regards to your precision, you can iterate through every PID folder in /proc and read the cmdline file. That's basically what ps does.

And by keeping track of the folder you're in, you can then get the pid.

Upvotes: 0

Marc Butler
Marc Butler

Reputation: 1376

If it is in C try looking at the sscanf standard library function. Documentation should be available through either via a man page on a Unix type system such as Linux, or an online reference such as the GNU C Reference.

Upvotes: 1

Giann
Giann

Reputation: 3192

Try replacing space characters with a unique separator. Then search for the PID column jumping from one separator to another.

Upvotes: 0

Related Questions