Skip to content

Instantly share code, notes, and snippets.

@xalexchen
Created July 2, 2014 02:28
Show Gist options
  • Save xalexchen/28be7d27fd92a070079c to your computer and use it in GitHub Desktop.
Save xalexchen/28be7d27fd92a070079c to your computer and use it in GitHub Desktop.
find_pid_by_name
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