简体   繁体   中英

Find out the process name by pid in osx kernel extension

I am working on kernel extension and want to find out how to find process name by pid in kernel extension

This code works great in user space

static char procdata[4096];
int mib[3] = { CTL_KERN, KERN_PROCARGS, pid };
procdata[0] = '\0'; // clear
size_t size = sizeof(procdata);
if (sysctl(mib, 3, procdata, &size, NULL, 0)) {
  return ERROR(ERROR_INTERNAL);
}
procdata[sizeof(procdata)-2] = ':';
procdata[sizeof(procdata)-1] = '\0';
ret = procdata;
return SUCCESS;

but for the kernel space, there are errors such as "Use of undeclared identifier 'CTL_KERN'" (even if I add #include )

What is the correct way to do it in kernel extension?

The Kernel.framework header <sys/proc.h> is what you're looking for.

In particular, you can use proc_name() to get a process's name given its PID:

/* this routine copies the process's name of the executable to the passed in buffer. It 
 * is always null terminated. The size of the buffer is to be passed in as well. This 
 * routine is to be used typically for debugging 
 */
void proc_name(int pid, char * buf, int size);

Note however, that the name will be truncated to MAXCOMLEN - 16 bytes.

You might also be able to use the sysctl via sysctlbyname() from the kernel. In my experience, that function doesn't work well though, as the sysctl buffer memory handling isn't expecting buffers in kernel address space, so most types of sysctl will cause a kernel panic if called from a non-kernel thread. It also doesn't seem to work for all sysctls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM