Linux根據程序名稱獲取pid

 

 

#include <sys/types.h>
#include <dirent.h>
#include<unistd.h>


#include <sys/stat.h>
#include <limits.h>
#include <stdio.h>


static int getPidOfProgram(const std::string & program)
{
		DIR* dir;
		struct dirent* ent;
		char buf[512];
		const char* name = program.c_str();
		long  pid;
		char pname[100] = { 0, };
		char state;
		FILE *fp = NULL;

		if (!(dir = opendir("/proc"))) {
			perror("can't open /proc");
			return -1;
		}

		while ((ent = readdir(dir)) != NULL) {
			long lpid = atol(ent->d_name);
			if (lpid < 0)
				continue;
			snprintf(buf, sizeof(buf), "/proc/%ld/stat", lpid);
			fp = fopen(buf, "r");

			if (fp) {
				if ((fscanf(fp, "%ld (%[^)]) %c", &pid, pname, &state)) != 3) {
					printf("fscanf failed \n");
					fclose(fp);
					closedir(dir);
					return -1;
				}
				if (!strcmp(pname, name)) {
					fclose(fp);
					closedir(dir);
					return (pid_t)lpid;
				}
				fclose(fp);
			}
		}
		closedir(dir);
		return -1;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章