September 22, 2013
In previous blog we discussed ruby code
where we used ps -ocommand
. In this blog let's discuss how to get arguments
passed to a command.
In the referred blog we are trying to find if --force
or -f
argument was
passed to the git push
command.
The kernel knows the arguments that was passed to the command. So the only way
to find that answer would be to ask kernel what was the full command. The tool
to deal with such issues is ps
.
In order to play with ps
command let's write a simple ruby program first.
# sl.rb
puts Process.pid
puts Process.ppid
sleep 99999999
In terminal execute ruby sl.rb
. In another terminal execute ps
.
$ ps
PID TTY TIME CMD
82246 ttys000 0:00.51 -bash
87070 ttys000 0:00.04 ruby loop.rb a, b, c
82455 ttys001 0:00.40 -bash
So here I have two bash shell open in two different tabs in my terminal. First
terminal tab is running s1.rb. The second terminal tab is running ps
. In the
second terminal we can see the arguments that were passed to program s1
.
By default ps
lists all the processes belonging to the user executing the
command and the processes started from the current terminal.
ps -p87070
would show result only for the given process id.
$ ps -p 87070
PID TTY TIME CMD
87070 ttys000 0:00.04 ruby loop.rb a, b, c
We can pass more than on process id.
$ ps -o pid,command -p87070,82246
PID COMMAND
82246 -bash
87070 ruby loop.rb a, b, c
ps -o
can be used to select the attributes that we want to be shown. For
example I want only pids to be shown.
$ ps -o pid
PID
82246
87070
82455
Now I want pid
and command
.
$ ps -o pid,command
PID COMMAND
82246 -bash
87070 ruby loop.rb a, b, c
82455 -bash
I want result only for a certain process id.
$ ps -o command -p87070
COMMAND
ruby loop.rb a, b, c
Now we have the arguments that were passed to the command. This is the code that article was talking about.
For the sake of completeness let's see a few more options.
ps -e
would list all processes.
$ ps -e
PID TTY TIME CMD
1 ?? 2:56.20 /sbin/launchd
11 ?? 0:01.90 /usr/libexec/UserEventAgent (System)
12 ?? 0:02.11 /usr/libexec/kextd
14 ?? 0:09.00 /usr/sbin/notifyd
15 ?? 0:05.81 /usr/sbin/securityd -i
........................................
........................................
ps -f
would list a lot more attributes including ppid
.
$ ps -f
UID PID PPID C STIME TTY TIME CMD
501 82246 82245 0 2:06PM ttys000 0:00.51 -bash
501 87070 82246 0 4:54PM ttys000 0:00.04 ruby loop.rb a, b, c
501 82455 82452 0 2:07PM ttys001 0:00.42 -bash
If this blog was helpful, check out our full blog archive.