Voting

The Note You're Voting On

webmaster at askapache dot com
11 years ago
On GNU/Linux you can retrieve the number of currently running processes on the machine by doing a stat for hard links on the '/proc' directory like so:

$ stat -c '%h' /proc
118

You can do the same thing in php by doing a stat on /proc and grabbing the [3] 'nlink' - number of links in the returned array.

Here is the function I'm using, it does a clearstatcache() when called more than once.

<?php

/**
* Returns the number of running processes
*
* @link http://php.net/clearstatcache
* @link http://php.net/stat Description of stat syntax.
* @author http://www.askapache.com/php/get-number-running-proccesses.html
* @return int
*/
function get_process_count() {
static
$ver, $runs = 0;

// check if php version supports clearstatcache params, but only check once
if ( is_null( $ver ) )
$ver = version_compare( PHP_VERSION, '5.3.0', '>=' );

// Only call clearstatcache() if function called more than once */
if ( $runs++ > 0 ) { // checks if $runs > 0, then increments $runs by one.

// if php version is >= 5.3.0
if ( $ver ) {
clearstatcache( true, '/proc' );
} else {
// if php version is < 5.3.0
clearstatcache();
}
}

$stat = stat( '/proc' );

// if stat succeeds and nlink value is present return it, otherwise return 0
return ( ( false !== $stat && isset( $stat[3] ) ) ? $stat[3] : 0 );
}

?>

Example #1 get_process_count() example

<?php
$num_procs
= get_process_count();
var_dump( $num_procs );
?>

The above example will output:

int(118)

Which is the number of processes that were running.

<< Back to user notes page

To Top