Mac OS X: Resolve absolute path using process’ PID

Mac OS X does not have a /proc file system. Therefore resolving the absolute path and other process informations have to be obtained in a different fashion. OS X has the libproc library, which can be used to gather different process informations. In order to find the absolute path for a given PID, the following code can be used:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <libproc.h>

int main (int argc, char* argv[])
{
	pid_t pid; int ret;
	char pathbuf[PROC_PIDPATHINFO_MAXSIZE];

	if ( argc > 1 ) {
		pid = (pid_t) atoi(argv[1]);
		ret = proc_pidpath (pid, pathbuf, sizeof(pathbuf));
		if ( ret <= 0 ) {
			fprintf(stderr, "PID %d: proc_pidpath ();\n", pid);
			fprintf(stderr,	"    %s\n", strerror(errno));
		} else {
			printf("proc %d: %s\n", pid, pathbuf);
		}
	}

	return 0;
}

I was surprised not to be able to easily find documentation for pid information, which in my opinion is quite trivial to be implemented. I had to go through the code of lsof to fing the implementation for reading proc txt section and finally learn about proc_pidinfo. proc_pidpath is just a wrapper for proc_pidinfo to resolve the path.

About these ads

2 thoughts on “Mac OS X: Resolve absolute path using process’ PID

  1. I’m trying to compile this under osx 10.8, and #include gives a ‘no such library or directory compile error’. And proc_pidpath won’t compile, probably because it’s in that include file. Any suggestions on what to change to get it to compile?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s