您的位置:首页 > 运维架构 > Linux

Linux获取进程pid

2016-03-16 19:08 579 查看
-/proc是系统中当前运行的所有进程的对应目录,以进程的 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