[申明]原创内容,转载请申明!
需要通过(部分)进程名查找PID,然后可以kill指定的进程了.
读取/proc/PID/cmdline 为完整进程名,即PS命令可以看到的进程名.
读取/proc/PID/stat 为进程各种信息.包括PID,部分进程名(不超过15字节),以及其他一些信息.
以下是主体部分.
int find_pid(char * process_name){
DIR *d;
struct dirent *de;
ssize_t readcount;
char tmp[256];
char tmp_name[256];
char pro_name[256];
char buffer[MAX_READ];
char name_buffer[256];
int pid;
int tmp_pid;
int fd,fd2;
if((d = opendir("/proc")) == 0)
return -1;
while((de = readdir(d)) != 0){
if(isdigit(de->d_name[0])){
pid = atoi(de->d_name);
sprintf(tmp,"/proc/%d/stat",pid);
sprintf(tmp_name,"/proc/%d/cmdline",pid);
fd = open(tmp,O_RDONLY);
if(fd == -1)
return -1;
readcount = read(fd, (void*)buffer, MAX_READ);
if(readcount == -1)
return -1;
close(fd);
fd2 = open(tmp_name,O_RDONLY);
if(fd2 == -1)
return -1;
readcount = read(fd2,(void*)name_buffer, 256);
if(readcount == -1)
return -1;
name_buffer[readcount] = '\0';
close(fd2);
if(name_buffer[0]){ //in default, the full process name is keep in /proc/PID/cmdline
if(!strcmp(name_buffer,process_name) || strstr(name_buffer,process_name) != NULL){
strcpy(full_proname,name_buffer);
return pid;
}
}
sscanf(buffer,"%d%*[^(](%[^)]",&tmp_pid,pro_name);
if(tmp_pid != pid)
return -1;
if(!strcmp(pro_name,process_name) || strstr(pro_name,process_name) != NULL){
return pid;
}else{
if(strlen(pro_name) == MAX_PROCESSNAME_INFILE && strlen(process_name) >= MAX_PROCESSNAME_INFILE)//the max length in stat/status of the [process name] value.
if(strstr(process_name,pro_name) != NULL)
return pid;
}
}
}