I had fun putting this together...
Code: Select all
/* Compile cmd: gcc -std=gnu99 -W -Wall -Werror -s -o getpids getpids.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glob.h>
unsigned getpids(char *pgm, int *pids, unsigned maxget, int (*cmp)(const char *,const char *))
{
glob_t g;
static char *line;
static size_t line_len;
if (glob("/proc/[1-9]*",0,0,&g))
perror("glob() failed!"),
exit(1);
char **names = g.gl_pathv;
unsigned nf = 0;
for (unsigned i=0; i < g.gl_pathc && nf < maxget; i++) {
char buff[100];
FILE *fp = fopen(strcat(strcpy(buff,*names++),"/stat"),"r");
if (!fp)
perror(buff),
exit(1);
getline(&line,&line_len,fp);
fclose(fp);
*strrchr(line,')') = 0;
if (!cmp(strchr(line,'(') + 1,pgm))
pids[nf++] = atoi(line);
}
globfree(&g);
return nf;
}
int main(void)
{
int the_pids[20];
unsigned num;
int my_strstr(const char *s1,const char *s2) {
return !strstr(s1,s2);
}
printf("Return value is: %d\n",num = getpids("bash",the_pids,20,strcmp));
for (unsigned i=0; i < num; i++)
printf("the_pids[%d] = %d\n",i,the_pids[i]);
}
Fixing any bugs or shortcomings in the above code is left as an exercise for the reader.
For starters, failure of the fopen() call should not be a fatal error, because of the "TOCTOU" problem.
Finally, as an exercise, try putting "my_strstr" instead of "strcmp" as the last arg to the getpids() call.