Skip to content

Instantly share code, notes, and snippets.

@shuchkin
Last active November 24, 2020 21:07
Show Gist options
  • Save shuchkin/00f93e249370566d820dc02da1926414 to your computer and use it in GitHub Desktop.
Save shuchkin/00f93e249370566d820dc02da1926414 to your computer and use it in GitHub Desktop.
Extract process name by PID
/**
* Get process by pid Windows|Linux
*
* @param int $pid PID or 0 to reset cache
* @param bool $disable_cache Disable cache for extracted process list (very slow)
*
* @return false|string
*/
function pid2proc( int $pid = 0, $disable_cache = false ) {
static $cache;
if ( $cache === null || $pid === 0 || $disable_cache ) { // reset cache
$cache = [];
// Windows ?
if ( strpos( PHP_OS, 'WIN' ) !== false ) {
exec( 'tasklist.exe /FO CSV', $output );
// "phpstorm64.exe","11500","Console","1","1239992 КБ"
foreach ( $output as $line ) {
$line = str_replace( '"', '', $line );
$a = explode( ',', $line );
if ( is_numeric( $a[1]) && $a[1] > 0 ) {
$cache[ $a[1] ] = $a[0];
}
}
} else {
exec( 'ps auxw', $output );
// root 1014 0.0 0.0 13020 772 ? Ssl Sep08 0:01 auditd
foreach ( $output as $line ) {
$line = preg_replace( '/\s+/', ' ', $line );
$a = explode( ' ', $line, 11 );
if ( is_numeric( $a[1] ) && $a[1] > 0) {
$cache[ $a[1] ] = $a[10];
}
}
}
}
return isset($cache[ $pid ]) ? $cache[ $pid ] : false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment