Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Fuser under perl

by lindex (Friar)
on Oct 12, 2000 at 06:04 UTC ( [id://36349]=CUFP: print w/replies, xml ) Need Help??

Well as far as I know there is no direct function or way to find processes using a file... so I wrote this, it could be bad code I dunno feel free to tell me, and also btw it should really only work on linux (or any other os that stores files open in /proc/pid/fd/file desc)
use Linux::Fuser;
Was this ugly mess from the year 2000:
package File::Fuser; use strict; use vars qw( @ISA @EXPORT ); use File::Spec; use Exporter; @ISA = qw(Exporter); @EXPORT = qw(fuser); sub fuser { my($file) = File::Spec->rel2abs($_[0]); my($f,@pids); foreach(glob("/proc/*")) { if ($_ =~ /^\/proc\/\d+$/) { foreach $f(glob("$_/fd/*")) { if ((reverse(File::Spec->splitpath($f)))[0] > 3 && -l +$f) { if (readlink($f) eq $file) { push(@pids,(reverse(File::Spec->splitpath($_)) +)[0]); } } } } } return((@pids)? @pids : -1); } 1;

Replies are listed 'Best First'.
RE: Fuser under perl
by Fastolfe (Vicar) on Oct 12, 2000 at 18:07 UTC
    There is also the (relatively) standard Unix utility lsof, which describes each of the open file descriptors for processes. This has the added benefit of identifying network sockets as well as true files.
      the point of this post was to show how this could be done completly under perl, of course there are util for this sorta stuff. but its more fun and prolly faster to do it complety in perl :)


      lindex
      /****************************/ jason@gost.net, wh@ckz.org http://jason.gost.net /*****************************/
Re: Fuser under perl
by Anonymous Monk on Mar 11, 2009 at 18:42 UTC
    There is a bug in your code.
    stdin, stdout, and stderr are fd's 0, 1, and 2.
    Thus, the line:

    if ((reverse(File::Spec->splitpath($f)))[0] > 3 && -l $f) {

    should be:

    if ((reverse(File::Spec->splitpath($f)))[0] >= 3 && -l $f) {
Re: Fuser under perl
by Aristotle (Chancellor) on Oct 29, 2002 at 20:22 UTC
    Note that the /proc tree is (mainly) a Linux characteristic and not availble on every Unixish system (let alone the non-Unixish ones).

    Makeshifts last the longest.

      Why repeat what other have said, why not read the description?
      Brought to you by that crazy but lovable guy... lindex

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://36349]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2024-04-23 06:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found