由进程名字获取进程 ID
程序员文章站
2024-02-20 11:08:22
...
方法一:
pid_t getProcessPidbyName(char *name)
{
FILE *fptr;
char *buf = new char[255];
char cmd[255] = {'\0'};
pid_t pid = -1;
sprintf(cmd,"pidof %s",name);
if((fptr = popen(cmd,"r")) != NULL)
{
if(fgets(buf,255,fptr) != NULL)
{
pid = atoi(buf);
printf("pid = %d\n",pid);
}
}
pclose(fptr);
delete buf;
return pid;
}
/**********************************************************
* 来自:http://blog.csdn.net/bulreed/article/details/6682811
*
***********************************************************/
方法二:
int main()
{
FILE *fp_handle;
DIR *process_dir;
struct dirent *ptr;
SVPBool process_flag = SVP_FALSE;
SVPChar buf[256] = {'\0'};
SVPChar filepath[128] = {'\0'};
SVPChar cur_task_name[128] = {'\0'};
process_dir = opendir("/proc");
if (SVP_NULL != process_dir)
{
while((ptr = readdir(process_dir)) != SVP_NULL) //循环读取路径下的每一个文件/文件夹
{
//如果读取到的是"."或者".."则跳过,读取到的不是文件夹名字也跳过
if(DT_DIR != ptr->d_type)
continue;
if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0))
continue;
if(atoi(ptr->d_name) < 1130)
continue;
sprintf(filepath, "/proc/%s/status", ptr->d_name);//生成要读取的文件的路径
fp_handle = fopen(filepath, "r");//打开文件
if (NULL != fp_handle)
{
if( fgets(buf, 255, fp_handle)== SVP_NULL ){ //如果文件夹为空就跳过
fclose(fp_handle);
continue;
}
sscanf(buf, "%*s %s", cur_task_name);
//如果文件内容满足要求则打印路径的名字(即进程的PID)
if (strcmp(SVP_RCHMI_PROCESS_NAME, cur_task_name) == 0)
{
process_flag = SVP_TRUE;
printf("PID: %s\n", ptr->d_name);
fclose(fp_handle);
break;
}
}
}
}
closedir(process_dir);//关闭路径
return process_flag;
}
上一篇: . Cascade Classifier
下一篇: 微服务启动jar包脚本