Skip to content

Instantly share code, notes, and snippets.

@scriptum
Last active December 14, 2022 06:10
Show Gist options
  • Save scriptum/6495260 to your computer and use it in GitHub Desktop.
Save scriptum/6495260 to your computer and use it in GitHub Desktop.
Getting PID of process by its command name in Linux-like OS.
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
/*
* This is example of getting PID of process by name. Returns first matched PID or -1.
* */
int getPidByName(const char *name)
{
char exe_file[] = "/proc/1000000000/exe";
char exe_path[256];
if(NULL == name)
return -1;
DIR* dir = opendir("/proc");
if(NULL == dir)
return -1;
struct dirent* de = 0;
while((de = readdir(dir)) != 0)
{
if(strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
continue;
int pid = -1;
int res = sscanf(de->d_name, "%d", &pid);
if(res != 1)
continue;
snprintf(exe_file, sizeof(exe_file), "/proc/%d/exe", pid);
ssize_t n = readlink(exe_file, exe_path, sizeof(exe_path));
if(n == -1)
continue;
exe_path[n] = '\0';
// puts(exe_path);
if(strstr(exe_path, name) != 0)
{
closedir(dir);
return pid;
}
}
closedir(dir);
return -1;
}
int main(int argc, char** argv)
{
if(argc != 2)
{
printf("%s: process_name\n", argv[0]);
exit(1);
}
printf("%d\n", getPidByName(argv[1]));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment