Skip to content

February 7, 2009

Making the most of unix commands when programming (Part 1) – the ps command

by Joe Kuan

unixWith the use of unix commands not only can reduce programming effort, but also if we utilise the them even more, less code is needed. Less code means less bugs. The well known unix tools philosophy is to ‘do one thing and do it well’. All we need is to make the tool doing well for our programs. In this article, I will give some examples in C and Php.

Some of the common tasks that we use unix tools are to:

  • find out whether a program is running, the process id of a running program, etc
  • find out system information: such as network, disk usage, etc

PS

Following is an example of C pseudo code that I have seen before.

FILE *fp = NULL;

if ((fp = popen(“ps -efl | grep -v grep | grep foo”, “r”)) != NULL) {
while (fgets(…) != NULL) {
<parse output code>
};
fclose(fp);
}

As you can see, the usage of the unix command is overkill. The parse output code portion was used for two jobs:

  1. counting the number of lines to find out whether a program is running
  2. parsing the output to get the process id

For doing 1, there is no need for checking the output of the ps command. The exit code of the command is enough. So the above code can be simplified by issuing command

For Linux, “ps -C foo -opid=”
For FreeBSD, “pgrep foo”

In C,

int rc = system(“ps -C foo”);
rc = WEXITSTATUS(rc);

In php,

system(“ps -C foo”, $rc);

If rc has zero value, then it means that the program foo is running. Otherwise, it is not. For more details, see man pages on system and wait4.

As for 2 – getting the process id(s), the unix command line will only return the process id value(s) without any other text.

In C, this would be the same as the above popen example except that the parse output code would become a lot simpler.

In php,

exec(“ps -C foo -opid=”, $out, $rc);

OR for getting a single pid value

$pidStr = trim(system(“ps -C foo -opid=”, $rc));

 

I work for iTrinegy and here are my other technical blogs

Read more from Unix

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

%d bloggers like this: