2

I was initially trying to use getpid() in my kernel module for OS X/macOS, is there a way to get the PID (process ID) of the process in whose context my kext is running in the kernel? Is there an existing function or variable that I can use ?

pmdj
  • 22,018
  • 3
  • 52
  • 103
Anurag
  • 651
  • 4
  • 18
  • See https://stackoverflow.com/questions/41676/is-there-a-way-of-getting-the-process-id-of-my-c-application. It's available in unistd.h. – mattias Nov 13 '17 at 22:59
  • @AndrewHenle why would you think will I post this and dig so much into the libraries if I already did not google it #facepalm – Anurag Nov 13 '17 at 23:15
  • 1
    Because [searching Google for "getpid() on mac"](https://www.google.com/search?q=getpid()+on+mac) returns as its very first result [the Mac `getpid(2)` man page](http://www.manpages.info/macosx/getpid.2.html) which clearly states you need `#include ` and `#include `, neither of which are mentioned in your question. #facepalm indeed. – Andrew Henle Nov 13 '17 at 23:20
  • 1
    i got the issue I was trying this in the kernel and i think getpid() does not work for the kernel – Anurag Nov 13 '17 at 23:25
  • @AndrewHenle do u have any inputs on that ? – Anurag Nov 13 '17 at 23:30
  • 2
    The process ID of what? Kernel extensions aren't processes. –  Nov 13 '17 at 23:33
  • 1
    @duskwuff I need to print out the PID of the process using my kext – Anurag Nov 13 '17 at 23:41
  • Well… what is your kernel extension? What would be "using" it? What context would its code be running in? –  Nov 14 '17 at 00:18
  • 1
    @AndrewHenle: The OP is not asking how to get the PID of the process their code is in, because their code is not part of a user process. They are asking how to get the PID of the process that initiated a request that caused their kernel extension to be invoked. – Eric Postpischil Nov 14 '17 at 01:57
  • 1
    Seems like a legit question to me. Whoever marked the question to be closed as "too broad": please consider that you might not have understood the question. You really shouldn't flag to close questions just because you don't know the answer. – pmdj Nov 14 '17 at 11:03

1 Answers1

1

To get the PID of the process with which the currently running kernel thread is associated, call the proc_selfpid() function; you'll need to #include <sys/proc.h> in your kext's code to get the prototype. The PID will of course only correspond to a user process if your code is running in the context of some kind of callback for a syscall.

pmdj
  • 22,018
  • 3
  • 52
  • 103