Ruby System Call
November 13th, 2007
So today for a customer we were faced with the problem of finding out of if a process was already running on a system. We toyed with several variations doing everything via shell script before executing the ruby script, but in the end we decided we needed to do it inside of the ruby script in order to use the custom logger that the project uses.
We found that a good article from Jay Fields on system calls from Ruby. We decided that %x was exactly what we were looking for because we needed the return values.

The first part executes `ps ax` which will give back to stdout a list of the running processes.
The second part takes that output and executes `grep irb` which will give back to stdout all the processes containing the expression irb.
The last part takes that output and does a line count to see how many lines are returned. The trouble here is that three lines were returned even though only two irb processes are running. The reason is that the grep irb also shows up as a process containing irb. The great thing about unix is that there are ways to do about anything.
Doing the following:

Gives us the desired output. By adding that `grep -v grep` we are telling grep to eliminate lines that have grep. This now gives us the desired result of 1. Now we can accurately tell if a process is already running. More specifics on the unix part of this can be found here.




November 14th, 2007 at 01:17 AM and if you don't like the %x{ blah blah} syntax you can always use the back ticks: `ps ax|grep -v grep | grep irbc |wc -1`