Linux获取进程pid
2016-03-16 19:08
579 查看
-/proc是系统中当前运行的所有进程的对应目录,以进程的 PID号为目录名,可用来获取进程信息。
-/proc/pid/comm是对应pid号的进程名。
-/proc/pid/comm是对应pid号的进程名。
#include <stdio.h> #include <string.h> #include <dirent.h> #include <stdlib.h> int main(int argc, char* argv[]){ if(argc < 2){ printf("expected proc name\nusage:\t%s [proc name]\n",argv[0]); return -1; } if(strcmp(argv[1],"--help") == 0){ printf("usage:\t%s [proc name]\n",argv[0]); return 0; } #define READ_BUF_SIZE 64 DIR* dir; struct dirent* next; FILE* status; char file_name[READ_BUF_SIZE]; char proc_name[READ_BUF_SIZE]; dir = opendir("/proc"); if(!dir){ printf("open error /proc\n"); return -1; } while((next = readdir(dir)) != NULL){ if(!isdigit(*next->d_name)) continue; memset(file_name,0,READ_BUF_SIZE); memset(proc_name,0,READ_BUF_SIZE); sprintf(file_name,"/proc/%s/comm",next->d_name); if(!(status = fopen(file_name,"r"))){ printf("open error %s",file_name); continue; } fscanf(status, "%s",proc_name); if(strcmp(argv[1],proc_name) == 0){ printf("%d\n",atoi(next->d_name)); fclose(status); return atoi(next->d_name); } } fclose(status); return 0; }
相关文章推荐
- Linux socket 初步
- Linux Kernel 4.0 RC5 发布!
- linux lsof详解
- linux 文件权限
- Linux 执行数学运算
- 10 篇对初学者和专家都有用的 Linux 命令教程
- Linux 与 Windows 对UNICODE 的处理方式
- Ubuntu12.04下QQ完美走起啊!走起啊!有木有啊!
- 解決Linux下Android开发真机调试设备不被识别问题
- 运维入门
- 运维提升
- Linux 自检和 SystemTap
- Ubuntu Linux使用体验
- c语言实现hashmap(转载)
- Linux 信号signal处理机制
- linux下mysql添加用户
- Scientific Linux 5.5 图形安装教程
- Linux 下无损图片压缩小工具介绍