Diego Torres
Diego Torres

Reputation: 5308

Observe a Process of Unknown PID (no UI)

I've found this question, but even when is close to what I need, is useless

Basically, I have an app that needs to do something when another process (of known name) is launched and/or terminated, but i don't have the PID, so i can't set a kqueue to look for it.

I could do a while for "ps aux | grep processtolook | grep -v grep" command, but that's my last resort.

Any ideas?

Upvotes: 1

Views: 1188

Answers (3)

andrewdski
andrewdski

Reputation: 5505

Look at this answer: Determine Process Info Programmatically in Darwin/OSX. The libproc.h header file has proc_listpids which will get you all the pids. You can then get the pid information in a loop and using proc_pidinfo and check the name. Looking at the top source as suggested there might also be worthwhile. (The current verson is here http://www.opensource.apple.com/source/top/top-67/.)

Unfortunately, this is an undocumented interface and subject to change at any time. Also, it isn't the quickest thing, since you have to loop over all the processes in the system. In general, this isn't a great way to do this.

A better way might be to write a new processtolook that simply invoked the old one which you can move or rename. It could then notify you of the process start and stop. Is that a possibility?

Upvotes: 2

Mel
Mel

Reputation: 6167

On BSD you can use kvm_openfiles and kvm_getprocs to implement what you want. I don't know if it's available on OSX. If you have a pgrep program, look how it's implemented (src/bin/pkill.c).

Upvotes: 0

phoxis
phoxis

Reputation: 61940

If the target process/program name which you want the PID is "processtolook" then you can use pidof command to get the PID of that running program.

pidof processtolook

have a look at the pidof manual. This is a part of sysvinit-tools package.

EDIT1: Have a look at this code i found: http://programming-in-linux.blogspot.com/2008/03/get-process-id-by-name-in-c.html

This might help you get you the outline.

Upvotes: 1

Related Questions