android系统中各个部分获取进程名称的方法

驱动程序的加载函数DriverEntry是运行在System进程中的.通过PsGetCurrentProcess可以获取System进程的内核EPROCESS结构的地址,然后从该地址开始寻找"System"字符串.找到后,便是EPROCESS的进程名存放的偏移处.得到进程名在EPROCESS结构的偏移后,以后的进程调用驱动的时候,就可以直接在该偏移处获取当前进程名.代码如下:

DWORD GetProcessNameOffset()
{
    PEPROCESS curproc;
    DWORD procNameOffset;
    curproc = PsGetCurrentProcess();
    for(int i=0; i< 4096; i++)
    {
        if( !strncmp( "System", (PCHAR) curproc + i, strlen("System") ))
        {
           procNameOffset = i;
            return procNameOffset;
        }
    }
    return 0;
}
BOOL GetProcessName( PCHAR theName )
{
    PEPROCESS       curproc;
    char            *nameptr;
    ULONG           i;
    KIRQL           oldirql;

    if( gProcessNameOffset )
    {
        curproc = PsGetCurrentProcess();
        nameptr   = (PCHAR) curproc + ProcNameOffset;
        strncpy( theName, nameptr, NT_PROCNAMELEN );
        theName[NT_PROCNAMELEN] = 0; /**//* NULL at end */
        return TRUE;
    }
    return FALSE;
}

Android HAL层,可以这样使用:

Android.mk 添加 
LOCAL_SHARED_LIBRARIES:= \ 
   libbinder

HAL层中.c文件中:
#include <errno.h>
#include <fcntl.h>

#include <sys/ioctl.h>
#include <sys/types.h>

#include <hardware/lights.h>
#include <hardware/hardware.h>
#include <hardware/sunxi_display2.h>

#include <cutils/list.h>
#include <stdlib.h>
#include <sys/cdefs.h>
#include <cutils/properties.h>

#include <android/log.h>
#include <binder/IPCThreadState.h>
int fd = 0;
#define GET_CALLING_PID    (android::IPCThreadState::self()->getCallingPid())
void getCallingProcessName(char *name) 
{ 
   char proc_node[128]; 

   if (name == 0) 
   { 
       LOGE("error in params"); 
       return; 
   } 

   memset(proc_node, 0, sizeof(proc_node)); 
   sprintf(proc_node, "/proc/%d/cmdline", GET_CALLING_PID); 
   int fp = ::open(proc_node, O_RDONLY); 
   if (fp > 0) 
   { 
       memset(name, 0, 128); 
       ::read(fp, name, 128); 
       ::close(fp); 
       fp = 0; 
       LOGD("Calling process is: %s", name); 
   } 
   else 
   { 
       LOGE("Obtain calling process failed"); 
   } 
} 
char mProcessName[128]; 
   getCallingProcessName(mProcessName); 
   LOGD("openCameraDev calling_process = %s", mProcessName);

之后就可以在logcat中看对应进程具体是哪些进程在调用,如果以上程序放入HAL的light.cpp中,使用logcat -s lights即可看到哪个进程在调用。

猜你喜欢

转载自blog.csdn.net/jinron10/article/details/93843572