How does ps show the argv for all processes on Mac OS X?
Asked Answered
C

2

6

I'm trying to identify when a particular process is running, based on its arguments, on Mac OS X. There may be several processes running with the same name, but only one will have the arguments I'm looking for. The processes are not owned by the same user who will be running my code. They will not have modified their argv in any way.

The 'ps' command shows exactly the information that I need. But I would greatly prefer not to have to spawn 'ps' and parse its output.

I originally tried the solution from this question, using sysctl, but it turns out that only works for processes you own; see my other question for more info.

So how does ps obtain argv information for processes owned by other users?

Corder answered 2/4, 2010 at 20:13 Comment(0)
S
5

On Mac OS X ps is setuid 0, which is how it gets the information for all the processes. You have to run as root to get that information, so either you need to be setuid 0 or run your utility with sudo.

The best way is probably just to spawn ps and parse the output, even if you don't really want to ;)

Semitropical answered 2/4, 2010 at 20:53 Comment(2)
So it is; I hadn't noticed that. That solves the mystery at least; thanks.Corder
Also the sysctl key KERN_PROCARGS2 is listed as '__APPLE_API_UNSTABLE' so even if you can use sysctl it is subject to change at Apple's grim whim.Cytolysis
R
5

BSD ps (used in Mac OS X) uses kvm_getargv() to get the commandline arguments for a process.

Here is the actual call: ps source code. Search for kvm_getproc2.

See OpenBSD man page for this family of functions.

Reece answered 2/4, 2010 at 20:38 Comment(2)
Apple's version is here: opensource.apple.com/source/adv_cmds/adv_cmds-138.1/psBloodmobile
This is interesting, although libkvm is deprecated (and headers unavailable) from 10.5 onwards. It also appears, based on Jason Coco's answer, that it may have the same limitation as sysctl.Corder
S
5

On Mac OS X ps is setuid 0, which is how it gets the information for all the processes. You have to run as root to get that information, so either you need to be setuid 0 or run your utility with sudo.

The best way is probably just to spawn ps and parse the output, even if you don't really want to ;)

Semitropical answered 2/4, 2010 at 20:53 Comment(2)
So it is; I hadn't noticed that. That solves the mystery at least; thanks.Corder
Also the sysctl key KERN_PROCARGS2 is listed as '__APPLE_API_UNSTABLE' so even if you can use sysctl it is subject to change at Apple's grim whim.Cytolysis

© 2022 - 2024 — McMap. All rights reserved.