Created
July 2, 2014 02:28
-
-
Save xalexchen/28be7d27fd92a070079c to your computer and use it in GitHub Desktop.
find_pid_by_name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int find_pid_of(const char *process_name) | |
{ | |
int id; | |
pid_t pid = -1; | |
DIR* dir; | |
FILE *fp; | |
char filename[32]; | |
char cmdline[256]; | |
struct dirent * entry; | |
if (process_name == NULL) | |
return -1; | |
dir = opendir("/proc"); | |
if (dir == NULL) | |
return -1; | |
while((entry = readdir(dir)) != NULL) { | |
id = atoi(entry->d_name); | |
if (id != 0) { | |
sprintf(filename, "/proc/%d/cmdline", id); | |
fp = fopen(filename, "r"); | |
if (fp) { | |
fgets(cmdline, sizeof(cmdline), fp); | |
fclose(fp); | |
if (strcmp(process_name, cmdline) == 0) { | |
/* process found */ | |
pid = id; | |
break; | |
} | |
} | |
} | |
} | |
closedir(dir); | |
return pid; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment