//get pid by process name
vector<int> get_pid_by_name(const char *name)
{
vector<int> vec;
DIR *dir = opendir("/proc/");
seekdir(dir, 2);
if (!dir)
{
perror("");
return vec;
}
struct dirent *dire = NULL;
char path[500] = "";
char buf[500] = "";
int pid = 0;
while((dire = readdir(dir)) != NULL)
{
if ((pid = atoi(dire->d_name)) == 0)
{
continue;
}
snprintf(path, 500, "/proc/%d/exe", pid);
int size = readlink(path, buf, 500);
if (size < 0)
{
continue;
}
buf[size] = 0;
char *ptr = strrchr(buf, '/');
string filename(ptr + 1, buf + size - ptr - 1);
if (filename.compare(name) == 0)
{
vec.push_back(pid);
}
}
closedir(dir);
return vec;
}
get pid by name
最新推荐文章于 2023-05-09 11:34:15 发布