1、查询 APP 的 PID
通过 遍历 proc 目录 下所有的进程查找我们要找的PID
static int find_pid(const char* process_name)
{
int pid = -1;
int temp = -1;
DIR *dir = opendir("/proc");
if (dir != NULL)
{
uint8_t buf[1024]; // large buffer for struct dirent (sizeof(dirent) does not include size of d_name)
struct dirent *entry, *result=NULL;
entry = (struct dirent *) buf;
for (;;)
{
if (readdir_r(dir, entry, &result) != EOK) break; // get next entry
if (result == NULL) break; // end of the directory stream reached
if (entry->d_namelen > 0) // name returned
{
char *end = NULL;
temp = strtoul(entry->d_name, &end, 10); // try to convert name to number to detect PID
if (*end == '\0')
{ // filename completely converted to number, this must be a PID
if ((pid_t) temp == getpid())
{
continue;// skip own id
}
// try to read the exe file name for this process and compare to
char buf[256];
snprintf(buf, sizeof(buf), "/proc/%s/exefile", entry->d_name); // create exefile path
int fd = open(buf, O_RDONLY);
if (fd >= 0)
{
int n = read(fd, buf, sizeof(buf) - 1); // read name
if (n > 0)
{
buf[n] = 0; // terminate string
if (strstr(buf, process_name) != NULL)
{ // searchtext found in name
pid = temp;
close(fd);
break;
}
}
close(fd); // close file
}
}
else
{
LOGD("Conversion failed: %s", entry->d_name);
}
}
}
closedir(dir); // cleanup
}
return pid;
}
2、kill 掉 APP
通过 获取 root 权限 kill 某个 app
static int kill_some_app(char * app_name, pid_t app_pid)
{
int status = -1;
int32_t oldUid = getuid();
uint8_t cnt = 0;
retry1:
if(setuid(0) != 0) {
if(cnt > 3) {
return -1;
}
cnt++;
LOGE("get root permision fail %d [%s]",cnt,strerror(errno));
goto retry1;
}
LOGE("get root permision success ");
LOGD("current need to kill %d app_name: %s app_pid: %d",cnt,app_name,app_pid);
cnt = 0;
retry2:
status = kill(app_pid, SIGTERM);
if(status != 0) {
if(cnt > 3) {
return -1;
}
cnt++;
LOGD("send signal SIGTGERM fail reason %d [%s]",cnt,strerror(errno));
goto retry2;
}
LOGD("send signal SIGTGERM success %d %s",cnt,app_name);
cnt = 0;
retry3:
if(setuid(oldUid) != 0)
{
if(cnt > 3) {
return -1;
}
cnt++;
LOGE("restore hostUpdate permision fail %d [%s]",cnt,strerror(errno));
goto retry3;
}
LOGE("restore hostUpdate permision success ");
return status;
}
3、KILL APP
for(i = 0; i < kill_list_info.app_num; i++) {
info[i].app_pid = find_pid(info[i].app_name);
if((info[i].app_pid != -1) && (info[i].app_pid > 0)) {
int ret = kill_some_app(info[i].app_name, info[i].app_pid);
if(ret != 0) {
return -1;
}
usleep(1 * 10000 * 1000); //wait 1s
}else {
LOGD("current system app_name: %s no start cur_pid: %d",info[i].app_name,info[i].app_pid);
}
}