根据PID获取进程状态
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/time.h>
#include<sys/resource.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include <utils/Log.h>
#include <dirent.h>
#include <ctype.h>
char getStatForPid(int pid)
{
#define MAX_FILE_LEN (256)
#define READ_BYTE (256)
char filePath[MAX_FILE_LEN] = {0};
sprintf(filePath, "/proc/%d/stat", pid);
int fd = open(filePath, O_RDONLY);
if (fd < 0) {
LOGE("vivo_daemon, Unable to open process file: %s\n", filePath);
return 'E';
}
char buffer[READ_BYTE];
const int len = read(fd, buffer, sizeof(buffer)-1);
close(fd);
if (len < 0) {
LOGE("vivo_daemon, Unable to open process file: %s fd=%d\n", filePath, fd);
return 'E';
}
buffer[len] = 0; //buffer:304 (system_server) S 126 126 0 0 -1 4194624 ...
//LOGD("vivo_daemon, buffer:%s", buffer);
//now to parse out pidstat
int spaceNum = 0;
char pidStat = 'E';
for(int i = 0; i < READ_BYTE; i++) {
if(' ' == buffer[i]) {
spaceNum++;
if(2 == spaceNum) {
pidStat = buffer[i+1];
break;
} else if(2 < spaceNum) {
break;
}
}
}
//LOGD("vivo_daemon, pidStat:%c", pidStat);
return pidStat;
}
原理非常简单,就是读取 /proc/[pid]/stat文件,然后从中解析出进程的状态。
有这个需求,主要是用来监视某一关键进程的状态,当其一旦长时间处于"T"时,则可发CONT消息,让其恢复"S"状态,这样便可使系统更多一重保护。(至于必要性的确有待商榷,毕竟是一个很不符合设计思想的亡羊补牢而已!)