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;
}
}
}