Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Create a pidof command to find PID numbers easily UNIX
After having working in UNIX enviroments for the past dozen years, when I got my new PowerBook, I was sorely dissapointed to find that there was no pidof command. Even with the Dev Tools, even with Fink, even with a week of searching Google. So I wrote my own.
#!/bin/sh
ps axc|awk "{if (\$5==\"$1\") print \$1}";
Place this in a script (/bin/pidof is a good idea) and chmod it 755 (chmod 755 /bin/pidof) (or 700 if you are paranoid). Once in place, you can find the PID number of any running program by typing (for example) pidof iTunes; if you want to kill a program, you can just type kill `pidof iTunes`.

A lot of the custom scripts I have written in the past years work well on OS X; in particular one program that I love is gjukebox, a web-based MP3 jukebox that works on OS X with a few tweaks -- except for the lack of a pidof command.

[robg adds: I tested this one, and it worked as expected.]
    •    
  • Currently 2.11 / 5
  You rated: 1 / 5 (9 votes cast)
 
[35,330 views]  

Create a pidof command to find PID numbers easily | 23 comments | Create New Account
Click here to return to the 'Create a pidof command to find PID numbers easily' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Create a pidof command to find PID numbers easily
Authored by: langer on Jun 19, '03 10:57:26AM
if you want to kill a program, you can just type kill `pidof iTunes`.
Or you could just use "killall iTunes", which is already there in /usr/bin.

-- Steve

[ Reply to This | # ]

Create a pidof command to find PID numbers easily
Authored by: zark on Oct 07, '04 01:38:24AM

the pidof command is already on your system. ever tried

ln -s /usr/bin/killall /usr/bin/pidof

with root privileges?

..this unix/linux world is weird, i know ;-)



[ Reply to This | # ]
Create a pidof command to find PID numbers easily
Authored by: foobar104 on Jun 19, '03 11:11:03AM

I'm not sure what you'd need this for other than to send a "kill" command (which doesn't necessarily kill a program; it just sends one of the defined signals).

If that's your goal, don't mess with this. Just use killall. It's just like kill, only takes a process name as an argument. If you wanted to kill iTunes (why??) you would type "killall iTunes".

As far as I know, killall first appeared in IRIX and then made it over to BSD, but that may not be true. IRIX is where I first encountered it.



[ Reply to This | # ]
Create a pidof command to find PID numbers easily
Authored by: englabenny on Jun 19, '03 11:18:34AM

It did not appear in Mac OS X before Jaguar, however.



[ Reply to This | # ]
Create a pidof command to find PID numbers easily
Authored by: robmorton on Jun 19, '03 11:38:13AM

Scroll down the hints a little farther. Suppose I want to renice and application. I need a process id to do that. Something along these lines, works very nice for renice as well.



[ Reply to This | # ]
Create a pidof command to find PID numbers easily
Authored by: adamjacobmuller on Jun 19, '03 01:22:50PM

<<author of the hint >>
this is a small bug in this hint, i'm not sure if it will create a problem however i am being preemptive.....

when you run pidof on a process name that has more than one process my pidof would return the pids delimited with \n's
this is not a good idea as the standard pidof would return the pids delimited by a space.
i fixed this by adding a "tr '\n' ' '"
then an echo on the end just to wrap the output

if that's confusing than dont worry
here's the revised code
<code>
#!/bin/sh
ps axc|awk "{if (\$5==\"$1\") print \$1}"|tr '\n' ' '
echo
</code>

also someone suggested that one could just killall <processname>
that's good but sometimes you might want to do
ps -p `pidof processname`
or something like that
or perhaps your just old and you are used to doing
kill -3 `pidof processname`
killall is good, pidof is good too. it's all about choice. that's what open source is all about.



[ Reply to This | # ]
Create a pidof command to find PID numbers easily
Authored by: ClarkGoble on Jun 19, '03 04:23:50PM

It's also useful if you've accidentally started too many processes of a command and just wish to kill one or two of them. Killall isn't that helpful there.



[ Reply to This | # ]
Create a pidof command to find PID numbers easily
Authored by: idle on Jun 19, '03 06:23:19PM

it's always the simplest things that are the best. After having used various unices over the last 10 years, I've always ps|grep'd.

sigh. it makes me feel like a newbie all over again.



[ Reply to This | # ]
Create a pidof command to find PID numbers easily
Authored by: adamjacobmuller on Jun 19, '03 08:54:52PM

not really, piping ps|grep is safe. I have been using linux for a decade and posix be dammed i have to re-learn commands all over again!
one of my favorite features is ps -C in linux this shows you all the proccess with the the specified name in darwin this has some obscure function that messed me up for two weeks i couldnt understand why it didn't work!!!!

so for you who is used to simply ps|grepping that's sometimes slower but better! becuse whether you move from darwin, to FreeBSD, to irix or linux or whatever i can assure you that ps and grep will still be present and will function in generally the same way (axuw commands generally are standardized at least)

I want to state so there is no confusion that this, someone who has used various unixes for a decade, love OSX any less! i love my little powerbook (12'). and i love the killer os that powers it. and critics be dammed even if microsoft cant make a decent os I happen to think that word is decent. and gimp will never live up to adobe photoshop. and ps2pdf never did as good a job as adobe acrobat! but at least i could type an entire document without the computer crashing, transform that 120mb tiff file, convert that 80page graphics intensive file to pdf without the computer crashing or locking up. but it was never the same. I missed that tactile response that windows gave me. I missed things looking good in linux. I reaized that things looking good took up too much processor power and i used the stripped down window manager now with my new powerbook i have the best of every world. Plus wireless networking that kicks butt! I will never abandon linux but at least I will never have to touch my mothers windows notebook again to get on that "supported browsers only" site.

got a wee bit off topic there... :-)



[ Reply to This | # ]
making pidof case insensitive?
Authored by: madgnome on Jun 20, '03 08:54:20AM

Hi, not to appear too lazy or stupid, but is there a way to make pidof case insensitive? I hate having to remember if something like itunes is iTunes or Itunes or iTuNeS or whatever.

I've always been a 'ps | grep -i' kind of person.

---
--Jeff



[ Reply to This | # ]
making pidof case insensitive?
Authored by: adamjacobmuller on Jun 21, '03 06:29:23PM

#!/bin/sh
ps axc|tr '[:upper:]' '[:lower:]'|awk "{if (\$5==\"`echo $1|\
tr '[:upper:]' '[:lower:]'`\") print \$1}"|tr '\n' ' '
echo


this makes all the output of ps axc lowercase then makes all your input lowercase so that it always matches regardless of case, this can be good this can be bad... i wonder if this is how the real pidof works? <<ssh's to his linux box to check>>
it's not, so it's probably not the best idea to do this, then again in most enviroments it would be unusual to have an uppercase letter... anywhere in the filename of a program.... so perhaps this isnt so bad.... it could just lead to false-positives.



[ Reply to This | # ]
making pidof case insensitive?
Authored by: dpwk on Jun 25, '03 06:16:23PM

My solution, short and reasonably sweet (I call it pidf):


#!/bin/sh
ps axc | grep -i $1 | awk "{ print \$1}";



[ Reply to This | # ]
script syntax appears to be wrong
Authored by: macubergeek on Jun 19, '03 10:38:58PM

Xmac-->ps axc | awk "{if ( \$5==\"$1\" ) print \$1}";
Unmatched ".
Xmac-->ps axc | awk "{if ( \$5==\"$1\" ) print \$1}"
Unmatched ".



[ Reply to This | # ]
script syntax appears to be wrong
Authored by: idle on Jun 20, '03 12:30:02AM

change the speech marks around the awk command from " to '.



[ Reply to This | # ]
script syntax appears to be wrong
Authored by: macubergeek on Jun 20, '03 10:14:00AM

Nah its correct, problem was I had a commented out line above the #!/bin/sh line...removed it and it worked fine.



[ Reply to This | # ]
A perl version
Authored by: rselph on Jun 21, '03 11:33:05AM
Adam's solution is more elegant, and more succinct than mine. But I'm more of a perl hacker, than a shell programmer. If you want a version that will match based on a regular expression, instead of an exact match, you can use this perl script:
#!/usr/bin/perl

@procs = `ps -x`;

for $proc (@procs ) {
    if( $proc =~ /\s+(\d+)\s+\S+\s+\S+\s+\S+\s+(\S+)/ ) {
	$pid = $1;
	$name = $2;
	if( $name =~ /$ARGV[0]/ ) {
	    print "$pid ";
	}
    }
}

print "\n";


[ Reply to This | # ]
A perl version
Authored by: adamjacobmuller on Jun 21, '03 06:32:15PM

ok, 45 secs between posts sucks...


the whole point of life is to have options, perhaps i want to integrate your solution into my new-fangled perl script in osx?

your idea is great too and by writing it your also making a valuable contribution. in open source every little piece comes together and makes this gigantic unstoppable whole.



[ Reply to This | # ]
A perl version
Authored by: adamjacobmuller on Jun 21, '03 06:59:38PM

hrmmm I think that osxhints strips \'s this is fixed...
I also changed
ps -x
to
ps -cxa


<code>
#!/usr/bin/perl
@procs = `ps -cxa`;
for $proc (@procs ) {
if( $proc =~ /\\s+(\\d+)\\s+\\S+\\s+\\S+\\s+\\S+\\s+(\\S+)/ ) {
$pid = $1;
$name = $2;
if( $name =~ /$ARGV[0]/ ) {
print "$pid ";
}
}
}

print "\\n";
</code>



[ Reply to This | # ]
A perl version
Authored by: adamjacobmuller on Jun 21, '03 07:01:13PM

the last one was wrong as well... i double quoted it.

this is RIGHT!!! I swear!!!!

<code>
#!/usr/bin/perl
@procs = `ps -cxa`;
for $proc (@procs ) {
if( $proc =~ /\s+(\d+)\s+\S+\s+\S+\s+\S+\s+(\S+)/ ) {
$pid = $1;
$name = $2;
if( $name =~ /$ARGV[0]/ ) {
print "$pid ";
}
}
}

print "\n";
</code>



[ Reply to This | # ]
A perl version
Authored by: adamjacobmuller on Jun 21, '03 07:07:56PM

any of the previous versions would match too much
if you looked for login it would match loginwindow
or theloginprocessname
any word with login in it
this is not a good idea
also this version is case-insensitive
<code>
#!/usr/bin/perl
$search=lc($ARGV[0]);
@procs = `ps -cxa`;
for $proc (@procs ) {
if( $proc =~ /\s+(\d+)\s+\S+\s+\S+\s+\S+\s+(\S+)/ ) {
$pid = $1;
$name = lc($2);
if( $name =~ /^$search$/ ) {
print "$pid ";
}
}
}

print "\n";
</code>

and this version is case-sensitive
<code>
#!/usr/bin/perl
$search=$ARGV[0];
@procs = `ps -cxa`;
for $proc (@procs ) {
if( $proc =~ /\s+(\d+)\s+\S+\s+\S+\s+\S+\s+(\S+)/ ) {
$pid = $1;
$name = $2;
if( $name =~ /^$search$/ ) {
print "$pid ";
}
}
}

print "\n";
</code>



[ Reply to This | # ]
A perl version
Authored by: adamjacobmuller on Jun 21, '03 07:19:19PM

the perl version is much faster too!
-------

case-insensitive bash&awk&tr version

bash-2.05a# time pidof httpd
337 348 385

real 0m0.169s
user 0m0.020s
sys 0m0.090s
----------------------------
bash&awk&tr case sensitive
bash-2.05a# time pidof httpd
337 348 385

real 0m0.094s
user 0m0.020s
sys 0m0.040s
----------------------------
perl case insensitive

bash-2.05a# time ./perl-pidof httpd
337 348 385

real 0m0.033s
user 0m0.000s
sys 0m0.030s
----------------------------
perl case sensitive
bash-2.05a# time ./perl-pidof-cs httpd
337 348 385

real 0m0.033s
user 0m0.010s
sys 0m0.020s

the verdict? pidof is fastest with the perl version which doesnt care if you want case sensitive or case insensitive output, what's my /bin/pidof now?
rselph's perl pidof function, case sensitive.



[ Reply to This | # ]
Create a pidof command to find PID numbers easily
Authored by: filipp on Nov 11, '06 04:02:45AM
I just stick this in my ~/.bash_profile:

pidof () { ps -Ac | egrep $@ | awk '{print $1}'; }

It's not a *strict* pidof because you can user partial process names, but for me, it's even more useful like this.

[ Reply to This | # ]
Create a pidof command to find PID numbers easily
Authored by: jdmuys on Oct 29, '09 07:00:20AM

This solution and the comments that I read have a flaw: they won't work for a command line tool.

The reason is that "ps -A" doesn't list command-line tools launched from the terminal. ("top" does, but that doesn't help much).

I wasn't able to find an option combination that would work for ps.

So are we stuck? Well, I found a way that works, inspired by this thread:

killall -s -c ToolName | grep -e [:digit:] | awk '{print $3}'

the idea is that killall -s will "simulate" the kill, and not do it. I then can parse the result.

As for the use case, mine is for the leaks command that wants a pid. When iterating on development, each run yields a different pid. so its useful to have a way to go from process name to pid.

Now I can do:

leaks `killall -s -c ToolName | grep -e [:digit:] | awk '{print $3}'`

Caveat: I'm really a Unix newbie. There might be a better solution. But mine works for me, while the previous ones didn't (on Snow Leopard).



[ Reply to This | # ]