unsigned int getpid(const char *process) {
int target_link;
DIR *dir_p;
DIR *dir_proc;
struct dirent *dir_entry_p;
struct dirent *dir_proc_p;
char dir_name[35];
char target_name[235];
char exe_link[235];
dir_p = opendir( "/proc/" ); /* Abre o /proc */
/* le os dirs do /proc */
while((dir_entry_p = readdir(dir_p)) != NULL) {
/* conta se so tem numeros no nome do dir */
if (strspn(dir_entry_p->d_name, "0123456789") == strlen(dir_entry_p->d_name)) {
sprintf(dir_name, "/proc/%s/", dir_entry_p->d_name);
/* Open that numbered directory */
if ((dir_proc = opendir(dir_name))) {
/* Reading its entries */
while ((dir_proc_p = readdir(dir_proc))) {
/* Check for that exe link file */
if (strncmp(dir_proc_p->d_name, "exe", 3) == 0) {
sprintf(exe_link, "%s%s", dir_name, dir_proc_p->d_name);
/* Getting the target of the exe ie to which binary it points to */
target_link = readlink(exe_link, target_name, sizeof(target_name));
target_name[target_link] = '\0';
/* Searching for process name in the target name */
if (strstr( target_name, process ) != NULL) {
closedir(dir_p);
return atoi(dir_entry_p->d_name);
}
strncpy(exe_link ,"", 1);
}
}
}
}
}
closedir(dir_p);
return 0;
}