PracticeDev/study_clang/Mimic/nos_monitor/getpidstate.c

92 lines
2.3 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "monitsys.h"
void getPidByName(pid_t *pid, char *task_name)
{
DIR *dir;
struct dirent *ptr;
FILE *fp;
char filepath[50];
char cur_task_name[50];
char buf[BUF_SIZE];
dir = opendir("/proc");
if (NULL != dir)
{
while ((ptr = readdir(dir)) != NULL) //循环读取/proc下的每一个文件/文件夹
{
//如果读取到的是"."或者".."则跳过,读取到的不是文件夹名字也跳过
if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0))
continue;
if (DT_DIR != ptr->d_type)
continue;
sprintf(filepath, "/proc/%s/status", ptr->d_name);//生成要读取的文件的路径
fp = fopen(filepath, "r");
if (NULL != fp)
{
if( fgets(buf, BUF_SIZE-1, fp)== NULL )
{
fclose(fp);
continue;
}
sscanf(buf, "%*s %s", cur_task_name); //如果文件内容满足要求则打印路径的名字即进程的PID
if (!strcmp(task_name, cur_task_name))
{
sscanf(ptr->d_name, "%d", pid);
}
fclose(fp);
}
}
closedir(dir);
}
}
FILE *getshellvalue(char *pcmd)
{
FILE * fstream = NULL;
if(NULL == (fstream = popen(pcmd,"r")))
{
fprintf(stdout,"execute command failed: ");
return NULL;
}
//pcmd = "ls -trl | awk '{print $9}'";
return fstream;
}
int main(void)
{
pid_t fpid; //fpid表示fork函数返回的值
pid_t fpid1;
char pcip[50]="\0",task_name[50]="\0",cmanager[50]="\0";
FILE *fp = NULL;
fp = fopen ("/root/cheng/initip.ini", "r");
if(fp == NULL)
{
printf("<p>open file:passwd.txt error</p>");
return 0;
}
// fscanf(fp,"%s %s %s %s",pcip,task_name,cmanager,manprocess);
fgets(pcip, sizeof(pcip), fp);
fgets(task_name, sizeof(task_name), fp);
fgets(cmanager, sizeof(cmanager), fp);
// fgets(manprocess, sizeof(manprocess), fp);
fclose(fp);
printf("name of task is %s\n",cmanager);
getPidByName(&pid, cmanager);
if (pid > 0)
{
printf("\nCapture dump function enable..\n");
printf("pid1:%d\n", pid);
}
else
{
printf("\nCapture dump function disable..\n");
printf("pid2:%d\n\n", pid);
}
return 0;
}