fuser in PHP

fuser is a handy command when you need to check if a file is currently opened by processes. Here is an implementation in PHP which will work on Linux by scanning the `/proc/<pids>/fd‘ sub-directories.

function fuser($file) {
  $pidList = array();
  if( ! is_dir('/proc') || ! is_readable('/proc') ) { return array(); }
  if( ($pDir = opendir('/proc')) === false ) { return array(); }
  while( ($pid = readdir($pDir)) !== false ) {
    if( ! preg_match('/^\d+$/', $pid) ) { continue; }
    $dir = sprintf('/proc/%s/fd', $pid);
    if( ! is_dir($dir) || ! is_readable($dir) ) { continue; }
    if( ($fdDir = opendir($dir)) === false ) { continue; }
    while( ($link = readdir($fdDir)) !== false ) {
      $link = sprintf('%s/%s', $dir, $link);
      if( is_link($link) && readlink($link) == $file ) { $pidList[] = $pid; break; }
    }
  }
  return $pidList;
}

This is specific to Linux, as on BSD (and Mac OS X) the information do not seems to be available in clear-form and requires some specific syscalls to get the information from the kernel VM…

Ce contenu a été publié dans code. Vous pouvez le mettre en favoris avec ce permalien.

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*