linux通过进程名获取进程id
2013-12-23 16:54
567 查看
/*************************************************************************** * File name : findpidbyname.c * Function : like pidof * Description : Find process's pid by name in linux. * ModifyRecord : ****************************************************************************/ #include <stdio.h> #include <sys/types.h> #include <dirent.h> #include <stdlib.h> #include <string.h> int find_pid_by_name( char* ProcName, int* foundpid) { DIR *dir; struct dirent *d; int pid, i; char *s; int pnlen; i = 0; foundpid[0] = 0; pnlen = strlen(ProcName); /* Open the /proc directory. */ dir = opendir("/proc"); if (!dir) { printf("cannot open /proc"); return -1; } /* Walk through the directory. */ while ((d = readdir(dir)) != NULL) { char exe [PATH_MAX+1]; char path[PATH_MAX+1]; int len; int namelen; /* See if this is a process */ if ((pid = atoi(d->d_name)) == 0) continue; snprintf(exe, sizeof(exe), "/proc/%s/exe", d->d_name); if ((len = readlink(exe, path, PATH_MAX)) < 0) continue; path[len] = '\0'; /* Find ProcName */ s = strrchr(path, '/'); if(s == NULL) continue; s++; /* we don't need small name len */ namelen = strlen(s); if(namelen < pnlen) continue; if(!strncmp(ProcName, s, pnlen)) { /* to avoid subname like search proc tao but proc taolinke matched */ if(s[pnlen] == ' ' || s[pnlen] == '\0') { foundpid[i] = pid; i++; } } } foundpid[i] = 0; closedir(dir); return 0; } int main(int argc, char *argv[]) { int i, rv, pid_t[128]; if ( argc != 2 ) { fprintf(stdout,"Usage %s procname\n",argv[0]); return 0; } rv = find_pid_by_name( argv[1], pid_t); if(!rv) { for(i=0; pid_t[i] != 0; i++) printf("%d\n", pid_t[i]); } return 0; }
相关文章推荐
- [linux基础] 通过进程id获取运行程序的程序名称
- linux 下获取进程ID 和 进程名
- 通过进程Id获取窗口句柄
- VC++ 通过进程名或进程ID获取进程句柄
- C通过管道获取LINUX进程内存占用情况
- 通过进程名获取进程ID
- java 获取进程ID 物理内存 cpu使用百分比(linux环境)
- 通过进程ID获取进程主窗口句柄
- Linux下普通用户获取端口与进程ID的关联
- VC++ 通过进程名或进程ID获取进程句柄
- linux根据进程名字获取进程ID
- Linux下获取当前进程的执行文件的绝对路径和所在目录(通过/proc/self/exe链接)
- 如何通过进程ID获取进程名
- 通过进程名称获取进程ID、通过子进程ID获取其父进程ID及通过进程ID获取进程名称
- linux -- 进程的查看、进程id的获取、进程的杀死
- 通过进程ID获取进程名
- linux 根据进程ID获取对应进程的信息
- 通过获取系统进程快照获取进程pid以及杀进程(win下获取进程名和linux下获取进程路径)
- WIN通过子进程获取父进程ID
- linux -- 进程的查看、进程id的获取、进程的杀死