#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 2004,2007 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 

# sr_lsfds - list file descriptors
#
# Usage1: sr_lsfds [file_path]
#
#   - lists all processes with open file descriptors to file_path
#
# Usage2: sr_lsfds
#
#   - lists all open file descriptors of all processes (best to
#     grep output for a specific PID)
#
#
# Each output line consists of:
#
# PID FD COMMAND NAME
#
# see "man lsof" for specific details of each of these fields.

open(LSOF, "lsof $ARGV[0] |");

while (<LSOF>)
{
	last;
}

$total_commands = 0;

while (<LSOF>)
{
	($command, $pid, $user, $fd, $type, $device, $size, $node, $name) = split;

	$i = 0;

	while ($i < $total_commands)
	{
		if ($command eq $commands[$i])
		{
			# eliminate same fd's in child processes

			if (index($fds[$i], $fd) > -1)
			{
				last;
			}
		}

		$i++;
	}

	if ($i < $total_commands)
	{
		next;
	}

	$commands[$total_commands] = $command;
	$fds[$total_commands] = $fd;

	$total_commands++;

	printf("%s %s %s %s\n", $pid, $fd, $command, $name);
}
