#include
#include
#include
#include
#include
#include
#include
#define READ_BUF_SIZE 1024
int find_pids_by_name(char *pidName, int *pids, int size)
{
DIR *dir;
struct dirent *next;
int i=0;
dir = opendir("/proc");
if (!dir)
{
fprintf(stderr, "Cannot open /proc\n");
exit(1);
}
while((next = readdir(dir)) != NULL)
{
FILE *status;
char filename[READ_BUF_SIZE];
char buffer[READ_BUF_SIZE];
char name[READ_BUF_SIZE];
// Must skip ".." since that is outside /proc
if (strcmp(next->d_name, "..") == 0)
continue;
// If it isn't a number, we don't want it
if (!isdigit(*next->d_name))
continue;
sprintf(filename, "/proc/%s/status", next->d_name);
if (! (status = fopen(filename, "r")))
continue;
// Read first line in /proc/?pid?/status
if (fgets(buffer, READ_BUF_SIZE-1, status) == NULL)
{
fclose(status);
continue;
}
fclose(status);
// Buffer should contain a string like "Name: binary_name"
sscanf(buffer, "%*s %s", name);
if (!strcmp(name, pidName))
{
*(pids+i) = strtol(next->d_name, NULL, 0);
i++;
}
}
return i;
}
int main()
{
int pids[10];
memset(pids, 0, sizeof(int)*10);
int ret, i;
ret=find_pids_by_name( "Parse", pids, 10);
printf("ncount->[%d]\n", ret);
for(i=0; i< ret; i++)
printf("pid[%d]->[%d]\n", i, pids[i]);
return 0;
}
阅读(920) | 评论(0) | 转发(0) |