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), h开发者_如何学Cow 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 */
}
}
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.
Try replacing space characters with a unique separator. Then search for the PID column jumping from one separator to another.
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.
精彩评论