LSOF(8)
๐ NAME ๐
lsof โ list open files. Yep, bestie, this is the lsof(8) page from your System Manager's Manual, and it's about to be your new fave for seeing what files are open. โจ
๐ SYNOPSIS ๐
lsof [ -?abChHlnNOPQRtUvVX ] [ -A A ] [ -c c ] [ +c c ] [ +|-d d ] [
+|-D D ] [ +|-e s ] [ +|-E ] [ +|-f [cfgGn] ] [ -F [f] ] [ -g [s] ] [ -i
[i] ] [ -k k ] [ -K k ] [ +|-L [l] ] [ +|-m m ] [ +|-M ] [ -o [o] ] [ -p
s ] [ +|-r [t[m<fmt>]] ] [ -s [p:s] ] [ -S [t] ] [ -T [t] ] [ -u s ] [
+|-w ] [ -x [fl] ] [ -z [z] ] [ -Z [Z] ] [ -- ] [names]
๐ฆ DESCRIPTION ๐ฆ
Lsof revision 4.99.7 lists on its standard output file information about files opened by processes for these UNIX dialects:
Apple Darwin 9, Mac OS X 10, macOS 11 and aboveFreeBSD 8.2 and aboveLinux 2.1.72 and aboveNetBSD 1.2 and aboveOpenBSD 7.2 and aboveSolaris 9, 10 and 11 and aboveOpenIndiana 5.11 and above
(See the DISTRIBUTION section of this manual page for information on how to obtain the latest lsof revision.) ๐ซถ
An open file may be a regular file, a directory, a block special file, a character special file, an executing text reference, a library, a stream or a network file (Internet socket, NFS file or UNIX domain socket.) A specific file or all the files in a file system may be selected by path. Literally so many file vibes. ๐
Instead of a formatted display, lsof will produce output that can be parsed by other programs. See the -F option description and the OUTPUT FOR OTHER PROGRAMS section for more information.
In addition to producing a single output list, lsof will run in repeat mode. In repeat mode it will produce output, delay, then repeat the output operation until stopped with an interrupt or quit signal. See the +|-r [t[m<fmt>]] option description for more information.
๐ OPTIONS ๐
In the absence of any options, lsof lists all open files belonging to all active processes. No options, no problem. ๐
If any list request option is specified, other list requests must be specifically requested โ e.g., if -U is specified for the listing of UNIX socket files, NFS files won't be listed unless -N is also specified; or if a user list is specified with the -u option, UNIX domain socket files, belonging to users not in the list, won't be listed unless the -U option is also specified.
Normally, list options that are specifically stated are ORed โ i.e., specifying the -i option without an address and the -ufoo option produces a listing of all network files OR files belonging to processes owned by user foo. The exceptions are:
- the
^(negated) login name or user ID (UID), specified with the-uoption; - the
^(negated) process ID (PID), specified with the-poption; - the
^(negated) process group ID (PGID), specified with the-goption; - the
^(negated) command, specified with the-coption; - the
^(negated) TCP or UDP protocol state names, specified with the-s [p:s]option.
Since they represent exclusions, they are applied without ORing or ANDing and take effect before any other selection criteria are applied. Exclusions go first, periodt. โจ
The -a option may be used to AND the selections. For example, specifying -a, -U, and -ufoo produces a listing of only UNIX socket files that belong to processes owned by user foo.
Caution: the-aoption causes all list selection options to be ANDed; it can't be used to cause ANDing of selected pairs of selection options by placing it between them, even though its placement there is acceptable. Wherever-ais placed, it causes the ANDing of all selection options. It's giving "one switch to AND them all." ๐
Items of the same selection set โ command names, file descriptors, network addresses, process identifiers, user identifiers, zone names, security contexts โ are joined in a single ORed set and applied before the result participates in ANDing. Thus, for example, specifying -i@aaa.bbb, -i@ccc.ddd, -a, and -ufff,ggg will select the listing of files that belong to either login fff OR ggg AND have network connections to either host aaa.bbb OR ccc.ddd.
Options may be grouped together following a single prefix โ e.g., the option set -a -b -C may be stated as -abC. However, since values are optional following +|-f, -F, -g, -i, +|-L, -o, +|-r, -s, -S, -T, -x and -z, when you have no values for them be careful that the following character isn't ambiguous. For example, -Fn might represent the -F and -n options, or it might represent the n field identifier character following the -F option. When ambiguity is possible, start a new option with a - character โ e.g., -F -n. If the next option is a file name, follow the possibly ambiguous option with -- โ e.g., -F -- name.
Either the + or the - prefix may be applied to a group of options. Options that don't take on separate meanings for each prefix โ e.g., -i โ may be grouped under either prefix. Thus, for example, +M -i may be stated as +Mi and the group means the same as the separate options. Be careful of prefix grouping when one or more options in the group does take on separate meanings under different prefixes โ e.g., +|-M; -iM is not the same request as -i +M. When in doubt, use separate options with appropriate prefixes. iykyk ๐ง
-?,-hโ these two equivalent options select a usage (help) output list. Lsof displays a shortened form of this output when it detects an error in the options supplied to it, after it has displayed messages explaining each error. (Escape the?character as your shell requires.)-aโ causes list selection options to be ANDed, as described above. The ultimate "AND" button. ๐-AA โ is available on systems configured for AFS whose AFS kernel code is implemented via dynamic modules. It allows thelsofuser to specify A as an alternate name list file where the kernel addresses of the dynamic modules might be found. See thelsofFAQ (the FAQ section gives its location) for more information about dynamic modules, their symbols, and how they affectlsof.-bโ causeslsofto avoid kernel functions that might block โlstat(2),readlink(2), andstat(2). See theBLOCKS AND TIMEOUTSandAVOIDING KERNEL BLOCKSsections for information on using this option.-cc โ selects the listing of files for processes executing the command that begins with the characters of c. Multiple commands may be specified, using multiple-coptions. They are joined in a single ORed set before participating in AND option selection.
If c begins with a ^, then the following characters specify a command name whose processes are to be ignored (excluded.)
If c begins and ends with a slash (/), the characters between the slashes are interpreted as a regular expression. Shell meta-characters in the regular expression must be quoted to prevent their interpretation by the shell. The closing slash may be followed by these modifiers:
bโ the regular expression is a basic one.iโ ignore the case of letters.xโ the regular expression is an extended one (default).
See the lsof FAQ (the FAQ section gives its location) for more information on basic and extended regular expressions.
The simple command specification is tested first. If that test fails, the command regular expression is applied. If the simple command test succeeds, the command regular expression test isn't made. This may result in no command found for regex: messages when lsof's -V option is specified.
+cw โ defines the maximum number of initial characters of the name, supplied by the UNIX dialect, of the UNIX command associated with a process to be printed in theCOMMANDcolumn. (Thelsofdefault is nine.)
Note that many UNIX dialects do not supply all command name characters to lsof in the files and structures from which lsof obtains command name. Often dialects limit the number of characters supplied in those sources. For example, Linux 2.4.27 and Solaris 9 both limit command name length to 16 characters.
If w is zero (0), all command characters supplied to lsof by the UNIX dialect will be printed.
If w is less than the length of the column title, COMMAND, it will be raised to that length.
-Cโ disables the reporting of any path name components from the kernel's name cache. See theKERNEL NAME CACHEsection for more information.+ds โ causeslsofto search for all open instances of directory s and the files and directories it contains at its top level.+ddoes NOT descend the directory tree, rooted at s. The+D Doption may be used to request a full-descent directory tree search, rooted at directory D.
Processing of the +d option does not follow symbolic links within s unless the -x or -x l option is also specified. Nor does it search for open files on file system mount points on subdirectories of s unless the -x or -x f option is also specified.
Note: the authority of the user of this option limits it to searching for files that the user has permission to examine with the system stat(2) function.
-ds โ specifies a list of file descriptors (FDs) to exclude from or include in the output listing. The file descriptors are specified in the comma-separated set s โ e.g.,cwd,1,3,^6,^2. (There should be no spaces in the set.)
The list is an exclusion list if all entries of the set begin with ^. It is an inclusion list if no entry begins with ^. Mixed lists are not permitted.
A file descriptor number range may be in the set as long as neither member is empty, both members are numbers, and the ending member is larger than the starting one โ e.g., 0-7 or 3-10. Ranges may be specified for exclusion if they have the ^ prefix โ e.g., ^0-7 excludes all file descriptors 0 through 7.
Multiple file descriptor numbers are joined in a single ORed set before participating in AND option selection.
When there are exclusion and inclusion members in the set, lsof reports them as errors and exits with a non-zero return code. No mixed lists, bestie โ pick a lane. ๐ญ
See the description of File Descriptor (FD) output values in the OUTPUT section for more information on file descriptor names.
fdโ bestie this is a pseudo file descriptor name, and it's here to stand in for the whole entire range of possible file descriptor numbers ๐ซ. Important:fddoes not show up in the FD column of output. It's a vibe, not a value.
+D Dโ tellslsofto go full detective mode ๐ and search for all open instances of directory D and all the files and directories it contains, all the way down to its complete depth. No skipping floors, she's checking every room.
Processing of the +D option does not follow symbolic links inside D unless the -x or -x l option is also specified. And it does not search for open files on file system mount points on subdirectories of D unless the -x or -x f option is also specified. Like, she respects the boundaries unless you tell her not to ๐ซถ
Note: the authority of whoever runs this option limits it to searching for files that user has permission to examine with the system stat(2) function. No sneaking past permissions, periodt.
Further note:lsofmay process this option slowly and need a large amount of dynamic memory to do it ๐ญ. Why? Because it has to descend the entire directory tree rooted at D, callingstat(2)for every file and directory, building a list of all the files it finds, and then searching that list for a match against every open file. When directory D is large, these steps can take a long time โ so use this option prudently, bestie. Like, think before you ship it.
-D Dโ directslsof's use of the device cache file. Using this option is sometimes restricted ๐ง. See the DEVICE CACHE FILE section and the sections that follow it for more info.
-D must be followed by a function letter, and that function letter may optionally be followed by a path name. lsof recognizes these function letters:
? - report device cache file paths
b - build the device cache file
i - ignore the device cache file
r - read the device cache file
u - read and update the device cache file
The b, r, and u functions, when accompanied by a path name, are sometimes restricted ๐. When these functions are restricted, they will not appear in the description of the -D option that accompanies -h or -? option output. See the DEVICE CACHE FILE section and the sections that follow it for more info on these functions and when they're restricted.
The ? function reports the read-only and write paths that lsof can use for the device cache file, the names of any environment variables whose values lsof will examine when forming the device cache file path, and the format for the personal device cache file path. (Escape the ? character as your shell requires โ shells are dramatic like that ๐
.)
When available, the b, r, and u functions may be followed by the device cache file's path. The standard default is .lsof_hostname in the home directory of the real user ID that executes lsof โ but this could have been changed when lsof was configured and compiled. (The output of the -h and -? options show the current default prefix, e.g., .lsof.) The suffix, hostname, is the first component of the host's name returned by gethostname(2) โจ.
When available, the b function directs lsof to build a new device cache file at the default or specified path.
The i function directs lsof to ignore the default device cache file and get its device info via direct calls to the kernel. Straight to the source, no middleman ๐ฅ.
The r function directs lsof to read the device cache at the default or specified path, but prevents it from creating a new device cache file when none exists or when the existing one is improperly structured. The r function, when specified without a path name, prevents lsof from updating an incorrect or outdated device cache file, or creating a new one in its place. The r function is always available when it's specified without a path name argument; it may be restricted by the permissions of the lsof process.
When available, the u function directs lsof to read the device cache file at the default or specified path if possible, and to rebuild it if necessary. This is the default device cache file function when no -D option has been specified ๐.
+|-e sโ exempts the file system whose path name is s from being subjected to kernel function calls that might block ๐. The+eoption exemptsstat(2),lstat(2)and mostreadlink(2)kernel function calls. The-eoption exempts onlystat(2)andlstat(2)kernel function calls. Multiple file systems may be specified with separate+|-especifications, and each one may havereadlink(2)calls exempted or not.
This option is currently implemented only for Linux ๐ง.
CAUTION: this option can easily be mis-applied to a file system other than the one you actually care about, because it uses path name rather than the more reliable device and inode numbers ๐ฌ. (Device and inode numbers are acquired via the potentially blockingstat(2)kernel call and are thus not available โ but see the+|-m moption as a possible alternative way to supply device numbers.) Use this option with great care and fully specify the path name of the file system to be exempted. Fully. Specify. It.
When open files on exempted file systems are reported, it may not be possible to get all their information. So some information columns will be blank, the characters UNKN preface the values in the TYPE column, and the applicable exemption option is added in parentheses to the end of the NAME column. (Some device number information might be made available via the +|-m m option.) It's giving "we tried our best" ๐ but honestly same.
+|-Eโ+Especifies that Linux pipe, Linux UNIX socket, Linux INET(6) socket closed in a local host, Linux pseudoterminal files, POSIX Message Queue implementation in Linux, and Linuxeventfdshould be displayed with endpoint information, and the files of the endpoints should also be displayed ๐.
Note 1: UNIX socket file endpoint information is only available when the features enabled line of-voutput containsuxsockept, and psudoterminal endpoint information is only available when the features enabled line containsptyept.
Note 2: POSIX Message Queue file endpoint information is only available when the mqueue file system is mounted.
Pipe endpoint information is displayed in the NAME column in the form PID,cmd,FDmode, where PID is the endpoint process ID; cmd is the endpoint process command; FD is the endpoint file's descriptor; and mode is the endpoint file's access mode ๐ธ.
Pseudoterminal endpoint information is displayed in the NAME column as ->/dev/ptsmin PID,cmd,FDmode or PID,cmd,FDmode. The first form is for a master device; the second, for a slave device. min is a slave device's minor device number; and PID, cmd, FD and mode are the same as with pipe endpoint information. Note: psudoterminal endpoint information is only available when the features enabled line of -v output contains ptyept. In addition, this feature works on Linux kernels above 4.13.0 โญ.
UNIX socket file endpoint information is displayed in the NAME column in the form type=TYPE ->INO=INODE PID,cmd,FDmode, where TYPE is the socket type; INODE is the i-node number of the connected socket; and PID, cmd, FD and mode are the same as with pipe endpoint information. Note: UNIX socket file endpoint information is available only when the features enabled line of -v output contains uxsockept.
INET socket file endpoint information is inserted into the value at the NAME column in the form -> PID,cmd,FDmode, where PID, cmd, FD and mode are the same as with pipe endpoint information. The endpoint information is available only if the socket is used for local IPC โ both endpoints bind to the same local IPv4 or IPv6 address ๐ฆ.
POSIX Message Queue file endpoint information is displayed in the NAME column in the same form as that of pipe.
eventfd endpoint information is displayed in the NAME column in the same form as that of pipe. This feature works on Linux kernels above 5.2.0 โจ.
Multiple occurrences of this information can appear in a file's NAME column. She's thorough, she's generous, she's iconic ๐ .
-E specifies that endpoint supported files should be displayed with endpoint information, but not the files of the endpoints. Half the tea, on purpose โ
+|-f [cfgGn]โfby itself clarifies how path name arguments are to be interpreted. When followed byc,f,g,G, ornin any combination, it specifies that the listing of kernel file structure information is to be enabled (+) or inhibited (-).
Normally a path name argument is taken to be a file system name if it matches a mounted-on directory name reported by mount(8), or if it represents a block device named in the mount output and associated with a mounted directory name. When +f is specified, all path name arguments will be taken to be file system names, and lsof will complain if any are not ๐ค. This can be useful, for example, when the file system name (mounted-on device) isn't a block device โ which happens for some CD-ROM file systems.
When -f is specified by itself, all path name arguments will be taken to be simple files. So, for example, the -f -- / arguments direct lsof to search for open files with a / path name, not all open files in the / (root) file system ๐ฅ.
Be careful to make sure+fand-fare properly terminated and aren't followed by a character (e.g., of the file or file system name) that might be taken as a parameter ๐ญ. For example, use--after+fand-fas in these examples:
$ lsof +f -- /file/system/name
$ lsof -f -- /file/name
Yeah okay so real talk: pulling info straight out of the kernel file structures โ the whole +f [cfgGn] option situation โ is normally inhibited, and honestly it's just not available, fully or partially, on some dialects. Like, for example, /proc-based Linux kernels below 2.6.22? Nope, sorry bestie. ๐
But when the prefix to f is a plus sign (+), these characters are the ones that request file structure info:
cโ file structure use count (not Linux)fโ file structure address (not Linux)gโ file flag abbreviations (Linux 2.6.22 and up)
And when you go with g, here's the whole flag glow-up โ abbrev on the left, the C code flag on the right (see open(2) for the lore):
WโO_WRONLYRWโO_RDWRCRโO_CREATEXCLโO_EXCLNTTYโO_NOCTTYTRโO_TRUNCAPโO_APPENDNDโO_NDELAYSYNโO_SYNCASYNโO_ASYNCDIRโO_DIRECTDTYโO_DIRECTORYNFLKโO_NOFOLLOWNATMโO_NOATIMEDSYNโO_DSYNCRSYNโO_RSYNCLGโO_LARGEFILECXโO_CLOEXECTMPFโO_TMPFILEGโ file flags in hexadecimal (Linux 2.6.22 and up)nโ file structure node address (not Linux)
When the prefix is a minus sign (-) instead? Same characters, but they disable the listing of those values. Flip mode. ๐
So why do you even care about file structure addresses, use counts, flags and node addresses? Because they let you clock identical files inherited by child processes way faster, and identical files being used by different processes too. Detective mode activated. ๐ต๏ธโโ๏ธ You can sort lsof's column output by the columns holding those values and list them to spot identical file use, or you can parse lsof field output with an AWK or Perl post-filter script, or with a C program. iykyk. โจ
-Ff โ this one specifies a character list, f, that picks exactly which fields get output for processing by another program, plus the character that terminates each output field. Each field you want output is specified with a single character in f. The field terminator defaults toNL, but it may be changed toNUL(000). Peep the OUTPUT FOR OTHER PROGRAMS section for the field identification characters and the whole field output process. ๐
When the field selection character list is empty, all standard fields are selected (except the raw device field, security context and zone field, for compatibility reasons) and the NL field terminator is used.
When the field selection character list contains only a zero (0), all fields are selected (except the raw device field, for compatibility reasons) and the NUL terminator character is used.
Any other combos of fields and their associated field terminator character have to be set with explicit entries in f, exactly as described in the OUTPUT FOR OTHER PROGRAMS section.
And here's a cute little bonus: when a field selection character identifies an item lsof does not normally list โ like PPID, selected with -R โ specifying that field character (like -FR) also selects the listing of the item. Two birds, one character. ๐ฆ
When the field selection character list contains the single character ?, lsof will show you a help list of the field identification characters. (Escape the ? character as your shell requires โ your shell is dramatic like that.)
-g[s] โ excludes or selects the listing of files for the processes whose optional process group IDentification (PGID) numbers are in the comma-separated set s โ e.g.,123or123,^456. (No spaces in the set, bestie, keep it tight.)
PGID numbers that start with ^ (negation) represent exclusions. ๐ซ
Multiple PGID numbers get joined into a single ORed set before they participate in AND option selection. But โ and this is the plot twist โ PGID exclusions are applied without ORing or ANDing and take effect before other selection criteria are applied.
Also -g enables the output display of PGID numbers. When specified without a PGID set? That's literally all it does. Iconic minimalism. ๐
-Hโ directs lsof to print human readable sizes, e.g.123.4K456.7M. Much cuter than a raw byte count, no cap. ๐-Jโ selects JSON output mode. Instead of the traditional tabular output or the-Ffield output, lsof produces a single JSON object on stdout containing aprocessesarray. Each process object contains its fields and afilesarray of open file entries. ๐
Field selection follows the same rules as -F: use -F with field characters to select which fields appear in the JSON output. Without -F, the default field set is used.
Heads up: -J is mutually exclusive with -j and -t. Warnings and errors are sent to stderr; stdout is always valid JSON (see the CHARACTER ENCODING NOTE below).
-jโ selects JSON Lines output mode. Each open file produces one JSON object per line, combining process and file fields in a single denormalized record. This format is suitable for streaming pipelines, log ingestion (Splunk, Datadog, Elastic), and line-oriented tools. ๐ฅฐ
Field selection follows the same rules as -J.
-j is mutually exclusive with -J and -t.
Character encoding note: JSON (RFC 8259) mandates that strings be valid UTF-8. However, file names on Unix-like systems are arbitrary byte sequences and may contain bytes that are not valid UTF-8. When such bytes appear, lsof passes them through to the output unchanged. This means the output is not strictly conformant JSON, but the original file name can be recovered. This is consistent with the behaviour oflsfd(1),ip(8)(-j), and other Linux utilities that produce JSON output. Consumers that require strict RFC 8259 conformance should filter or re-encode such values (e.g. usingiconv(1)or Python'ssurrogateescapeerror handler).
-i[i] โ selects the listing of files any of whose Internet address matches the address specified in i. If no address is specified, this option selects the listing of all Internet and x.25 (HP-UX) network files. ๐
If -i4 or -i6 is specified with no following address, only files of the indicated IP version โ IPv4 or IPv6 โ are displayed. (An IPv6 specification may be used only if the dialect supports IPv6, as indicated by [46] and IPv[46] in lsof's -h or -? output.) Sequentially specifying -i4, followed by -i6, is the same as specifying -i, and vice-versa. Specifying -i4, or -i6 after -i, is the same as specifying -i4 or -i6 by itself.
Multiple addresses (up to a limit of 100) may be specified with multiple -i options. (A port number or service name range is counted as one address.) They get joined into a single ORed set before participating in AND option selection.
An Internet address is specified in this form (items in square brackets are optional, so don't come for me):
[46][protocol][@hostname|hostaddr][:service|port]
where:
46โ specifies the IP version, IPv4 or IPv6, that applies to the following address.6may be specified only if the UNIX dialect supports IPv6. If neither4nor6is specified, the following address applies to all IP versions.protocolโ is a protocol name:TCP,UDPorUDPLITE.hostnameโ is an Internet host name. Unless a specific IP version is specified, open network files associated with host names of all versions will be selected.hostaddrโ is a numeric Internet IPv4 address in dot form; or an IPv6 numeric address in colon form, enclosed in brackets, if the UNIX dialect supports IPv6. When an IP version is selected, only its numeric addresses may be specified.serviceโ is an/etc/servicesname โ e.g.,smtpโ or a list of them.portโ is a port number, or a list of them.
IPv6 options may be used only if the UNIX dialect supports IPv6. Wanna check if your dialect is down with IPv6? Run lsof and specify the -h or -? (help) option. If the displayed description of the -i option contains [46] and IPv[46], IPv6 is supported. ๐ฆ
IPv4 host names and addresses may not be specified if network file selection is limited to IPv6 with -i 6. IPv6 host names and addresses may not be specified if network file selection is limited to IPv4 with -i 4. And when an open IPv4 network file's address is mapped in an IPv6 address, the open file's type will be IPv6, not IPv4, and its display will be selected by 6, not 4. Plot twist, but make it RFC. ๐ญ
At least one address component โ 4, 6, protocol, hostname, hostaddr, or service โ must be supplied. The @ character, leading the host specification, is always required; as is the :, leading the port specification. Specify either hostname or hostaddr. Specify either service name list or port number list. If a service name list is specified, the protocol may also need to be specified if the TCP, UDP and UDPLITE port numbers for the service name are different. Use any case โ lower or upper โ for protocol. ๐
Service names and port numbers may be combined in a list whose entries are separated by commas and whose numeric range entries are separated by minus signs. There may be no embedded spaces, and all service names must belong to the specified protocol. Since service names may contain embedded minus signs, the starting entry of a range can't be a service name; it can be a port number, however. Don't fight the rules, they're literally just vibes with syntax. ๐
Here are some sample addresses:
okay so we're still in the option zone, bestie โ picking up right in the middle of the -i example buffet, and the -i6 line is right there exactly where it belongs ๐
-i6 - IPv6 only
TCP:25 - TCP and port 25
@1.2.3.4 - Internet IPv4 host address 1.2.3.4
@[3ffe:1ebc::1]:1234 - Internet IPv6 host address
3ffe:1ebc::1, port 1234
UDP:who - UDP who service port
TCP@lsof.itap:513 - TCP, port 513 and host name lsof.itap
tcp@foo:1-10,smtp,99 - TCP, ports 1 through 10,
service name smtp, port 99, host name foo
tcp@bar:1-smtp - TCP, ports 1 through smtp, host bar
:time - either TCP, UDP or UDPLITE time service port
-Kk โ selects the listing of tasks (threads) of processes, on dialects where task (thread) reporting is supported. (If help output โ i.e., the output of the-hor-?options โ shows this option, then task (thread) reporting is supported by the dialect.)
If -K is followed by a value, k, it must be i. That causes lsof to ignore tasks, especially in the default, list-everything case when no other options are specified.
When -K and -a are both specified on Linux, and the tasks of a main process are selected by other options, the main process will also be listed as though it were a task, but without a task ID. (See the description of the TID column in the OUTPUT section.)
Where the FreeBSD version supports threads, all threads will be listed with their IDs.
In general threads and tasks inherit the files of the caller, but may close some and open others, so lsof always reports all the open files of threads and tasks.
-kk โ specifies a kernel name list file,k, in place of/vmunix,/mach, etc.-kis not available under AIX on the IBM RISC/System 6000.-lโ inhibits the conversion of user ID numbers to login names. It is also useful when login name lookup is working improperly or slowly. ngl, a little speed and fewer weird lookups? iconic.+|-L[l] โ enables (+) or disables (-) the listing of file link counts, where they are available โ e.g., they aren't available for sockets, or most FIFOs and pipes.
When +L is specified without a following number, all link counts will be listed. When -L is specified (the default), no link counts will be listed.
When +L is followed by a number, only files having a link count less than that number will be listed. (No number may follow -L.) A specification of the form +L1 will select open files that have been unlinked. A specification of the form +aL1 <file_system> will select unlinked open files on the specified file system.
For other link count comparisons, use field output (-F) and a post-processing script or program.
+|-mm โ specifies an alternate kernel memory file or activates mount table supplement processing.
The option form -m m specifies a kernel memory file, m, in place of /dev/kmem or /dev/mem โ e.g., a crash dump file.
The option form +m requests that a mount supplement file be written to the standard output file. All other options are silently ignored.
There will be a line in the mount supplement file for each mounted file system, containing the mounted file system directory, followed by a single space, followed by the device number in hexadecimal "0x" format โ e.g.,
/ 0x801
Lsof can use the mount supplement file to get device numbers for file systems when it can't get them via stat(2) or lstat(2).
The option form +m m identifies m as a mount supplement file.
Note: the+mand+m moptions are not available for all supported dialects. Check the output of lsof's-hor-?options to see if the+mand+m moptions are available. ๐ซถ
+|-Mโ Enables (+) or disables (-) the reporting of portmapper registrations for local TCP, UDP and UDPLITE ports, where port mapping is supported. (See the last paragraph of this option description for information about where portmapper registration reporting is supported.)
The default reporting mode is set by the lsof builder with the HASPMAPENABLED #define in the dialect's machine.h header file; lsof is distributed with the HASPMAPENABLED #define deactivated, so portmapper reporting is disabled by default and must be requested with +M. Specifying lsof's -h or -? option will report the default mode. Disabling portmapper registration when it is already disabled or enabling it when already enabled is acceptable. When portmapper registration reporting is enabled, lsof displays the portmapper registration (if any) for local TCP, UDP or UDPLITE ports in square brackets immediately following the port numbers or service names โ e.g., :1234[name] or :name[100083]. The registration information may be a name or number, depending on what the registering program supplied to the portmapper when it registered the port.
When portmapper registration reporting is enabled, lsof may run a little more slowly or even become blocked when access to the portmapper becomes congested or stopped. Reverse the reporting mode to determine if portmapper registration reporting is slowing or blocking lsof.
For purposes of portmapper registration reporting lsof considers a TCP, UDP or UDPLITE port local if: it is found in the local part of its containing kernel structure; or if it is located in the foreign part of its containing kernel structure and the local and foreign Internet addresses are the same; or if it is located in the foreign part of its containing kernel structure and the foreign Internet address is INADDR_LOOPBACK (127.0.0.1). This rule may make lsof ignore some foreign ports on machines with multiple interfaces when the foreign Internet address is on a different interface from the local one.
See the lsof FAQ (The FAQ section gives its location.) for further discussion of portmapper registration reporting issues.
Portmapper registration reporting is supported only on dialects that have RPC header files. (Some Linux distributions with GlibC 2.14 do not have them.) When portmapper registration reporting is supported, the -h or -? help output will show the +|-M option.
-nโ inhibits the conversion of network numbers to host names for network files. Inhibiting conversion may make lsof run faster. It is also useful when host name lookup is not working properly. speed boost era โจ-Nโ selects the listing of NFS files.-oโ directs lsof to display file offset at all times. It causes the SIZE/OFF output column title to be changed to OFFSET. Note: on some UNIX dialects lsof can't obtain accurate or consistent file offset information from its kernel data sources, sometimes just for particular kinds of files (e.g., socket files.) Consult the lsof FAQ (The FAQ section gives its location.) for more information.
The -o and -s options are mutually exclusive; they can't both be specified. When neither is specified, lsof displays whatever value โ size or offset โ is appropriate and available for the type of the file.
-oo โ defines the number of decimal digits (o) to be printed after the0tfor a file offset before the form is switched to0x.... Anovalue of zero (unlimited) directs lsof to use the0tform for all offset output.
This option does NOT direct lsof to display offset at all times; specify -o (without a trailing number) to do that. -o o only specifies the number of digits after 0t in either mixed size and offset or offset-only output. Thus, for example, to direct lsof to display offset at all times with a decimal digit count of 10, use: -o -o 10 or -oo10.
The default number of digits allowed after 0t is normally 8, but may have been changed by the lsof builder. Consult the description of the -o o option in the output of the -h or -? option to determine the default that is in effect.
-Oโ directs lsof to bypass the strategy it uses to avoid being blocked by some kernel operations โ i.e., doing them in forked child processes. See the BLOCKS AND TIMEOUTS and AVOIDING KERNEL BLOCKS sections for more information on kernel operations that may block lsof.
While use of this option will reduce lsof startup overhead, it may also cause lsof to hang when the kernel doesn't respond to a function. Use this option cautiously. fr fr, caution is the vibe here ๐จ
-ps โ excludes or selects the listing of files for the processes whose optional process IDentification (PID) numbers are in the comma-separated setsโ e.g.,123or123,^456. (There should be no spaces in the set.)
PID numbers that begin with ^ (negation) represent exclusions.
Multiple process ID numbers are joined in a single ORed set before participating in AND option selection. However, PID exclusions are applied without ORing or ANDing and take effect before other selection criteria are applied.
-Pโ inhibits the conversion of port numbers to port names for network files (the mapping is commonly learned from/etc/services). Inhibiting the conversion may make lsof run a little faster. It is also useful when port name lookup is not working properly.-Qโ ignore failed search terms. When lsof is told to search for users of a file, or for users of a device, or for a specific PID, or for certain protocols in use by that PID, and so on, lsof will return an error if any of the search results are empty. The-Qoption will change this behavior so that lsof will instead return a successful exit code (0) even if any of the search results are empty. In addition, missing search terms will not be reported tostderr. quiet success arc, we love to see it ๐+|-r [t[c<N>][m<fmt>]]โ okay so this one is the repeat mode icon โจ it literally putslsofin repeat mode. Here's the vibe:lsoflists open files as selected by your other options, delaystseconds (default is fifteen, bestie), then repeats the listing, delaying and listing over and over until a condition defined by the prefix to the option stops it.
If the prefix is -, repeat mode is endless ๐ญ you must terminate lsof with an interrupt or quit signal. c<N> is for specifying the limits of repeating โ if the number of iterations reaches <N>, Lsof stops itself, no drama.
If the prefix is +, repeat mode will end the first cycle no open files are listed โ and of course when lsof is stopped with an interrupt or quit signal. When repeat mode ends because no files are listed, the process exit code will be zero if any open files were ever listed; one, if none were ever listed. Periodt.
Lsof marks the end of each listing: if field output is in progress (the -F option has been specified), the default marker is m; otherwise the default marker is ========. The marker is followed by a NL character.
The optional m<fmt> argument specifies a format for the marker line. The <fmt> characters following m are interpreted as a format specification to strftime(3), when both it and the localtime(3) function are available in the dialect's C library. Consult the strftime(3) documentation for what may appear in its format specification. Note that when field output is requested with the -F option, <fmt> cannot contain the NL format, %n. Note also that when <fmt> contains spaces or other characters that affect the shell's interpretation of arguments, <fmt> must be quoted appropriately. ๐
Repeat mode reduces lsof startup overhead, so it is more efficient to use this mode than to call lsof repetitively from a shell script, for example. Highkey a glow-up for your script.
To use repeat mode most efficiently, accompany +|-r with specification of other lsof selection options, so the amount of kernel memory access lsof does will be kept to a minimum. Options that filter at the process level โ e.g., -c, -g, -p, -u โ are the most efficient selectors. Slay.
Repeat mode is useful when coupled with field output (see the -F option description) and a supervising awk or Perl script, or a C program. ๐ฆ
-Rโ directslsofto list the Parent Process IDentification number in thePPIDcolumn. Simple, iconic, done.-s [p:s]โsalone directslsofto display file size at all times. It causes theSIZE/OFFoutput column title to be changed toSIZE. If the file does not have a size, nothing is displayed. ๐
The optional -s p:s form is available only for selected dialects, and only when the -h or -? help output lists it.
When the optional form is available, the s may be followed by a protocol name (p), either TCP or UDP, a colon (:) and a comma-separated protocol state name list, the option causes open TCP and UDP files to be excluded if their state name(s) are in the list (s) preceded by a ^; or included if their name(s) are not preceded by a ^.
Dialects that support this option may support only one protocol. When an unsupported protocol is specified, a message will be displayed indicating state names for the protocol are unavailable. ๐
When an inclusion list is defined, only network files with state names in the list will be present in the lsof output. Thus, specifying one state name means that only network files with that lone state name will be listed.
Case is unimportant in the protocol or state names, but there may be no spaces and the colon (:) separating the protocol name (p) and the state name list (s) is required. No cap.
If only TCP and UDP files are to be listed, as controlled by the specified exclusions and inclusions, the -i option must be specified, too. If only a single protocol's files are to be listed, add its name as an argument to the -i option.
For example, to list only network files with TCP state LISTEN, use:
-iTCP -sTCP:LISTEN
Or, for example, to list network files with all UDP states except Idle, use:
-iUDP -sUDP:^Idle
State names vary with UNIX dialects, so it's not possible to provide a complete list. Some common TCP state names are: CLOSED, IDLE, BOUND, LISTEN, ESTABLISHED, SYN_SENT, SYN_RCDV, ESTABLISHED, CLOSE_WAIT, FIN_WAIT1, CLOSING, LAST_ACK, FIN_WAIT_2, and TIME_WAIT. Two common UDP state names are Unbound and Idle. Apple Darwin does not provide UDP state info to lsof. ๐
See the lsof FAQ (The FAQ section gives its location.) for more information on how to use protocol state exclusion and inclusion, including examples.
The -o (without a following decimal digit count) and -s option (without a following protocol and state name list) are mutually exclusive; they can't both be specified. When neither is specified, lsof displays whatever value โ size or offset โ is appropriate and available for the type of file.
Since some types of files don't have true sizes โ sockets, FIFOs, pipes, etc. โ lsof displays for their sizes the content amounts in their associated kernel buffers, if possible. The way that's handled is genuinely so extra. ๐ซถ
-S [t]โ specifies an optional time-out seconds value for kernel functions โlstat(2),readlink(2), andstat(2)โ that might otherwise deadlock. The minimum fortis two; the default, fifteen; when no value is specified, the default is used.
See the BLOCKS AND TIMEOUTS section for more information.
-T [t]โ controls the reporting of some TCP/TPI information, also reported bynetstat(1), following the network addresses. In normal output the information appears in parentheses, each item exceptTCPorTPIstate name identified by a keyword, followed by=, separated from others by a single space:
<TCP or TPI state name>
QR=<read queue length>
QS=<send queue length>
SO=<socket options and values>
SS=<socket states>
TF=<TCP flags and values>
WR=<window read length>
WW=<window write length>
Not all values are reported for all UNIX dialects. Items values (when available) are reported after the item name and =.
When the field output mode is in effect (See OUTPUT FOR OTHER PROGRAMS.) each item appears as a field with a T leading character.
-T with no following key characters disables TCP/TPI information reporting.
-T with following characters selects the reporting of specific TCP/TPI information:
fโ selects reporting of socket options, states and values, and TCP flags and values.qโ selects queue length reporting.sโ selects connection state reporting.wโ selects window size reporting.
Not all selections are enabled for some UNIX dialects. State may be selected for all dialects and is reported by default. The -h or -? help output for the -T option will show what selections may be used with the UNIX dialect.
When -T is used to select information โ i.e., it is followed by one or more selection characters โ the displaying of state is disabled by default, and it must be explicitly selected again in the characters following -T. (In effect, then, the default is equivalent to -Ts.) For example, if queue lengths and state are desired, use -Tqs. Sneaky but fair. ๐
Socket options, socket states, some socket values, TCP flags and one TCP value may be reported (when available in the UNIX dialect) in the form of the names that commonly appear after SO_, so_, SS_, TCP_ and TF_ in the dialect's header files โ most often <sys/socket.h>, <sys/socketvar.h> and <netinet/tcp_var.h>. Consult those header files for the meaning of the flags, options, states and values.
SO='' precedes socket options and values; SS='', socket states; and ``TF='', TCP flags and values.
If a flag or option has a value, the value will follow an = and the name โ e.g., SO=LINGER=5'', SO=QLIM=5'', ``TF=MSS=512''. The following seven values may be reported:
Name
Reported Description (Common Symbol)
KEEPALIVE keep alive time (SO_KEEPALIVE)
LINGER linger time (SO_LINGER)
MSS maximum segment size (TCP_MAXSEG)
PQLEN partial listen queue connections
QLEN established listen queue connections
QLIM established listen queue limit
RCVBUF receive buffer length (SO_RCVBUF)
SNDBUF send buffer length (SO_SNDBUF)
Details on what socket options and values, socket states, and TCP flags and values may be displayed for particular UNIX dialects may be found in the answer to the Why doesn't lsof report socket options, socket states, and TCP flags and values for my dialect?'' and Why doesn't lsof report the partial listen queue connection count for my dialect?'' questions in the lsof FAQ (The FAQ section gives its location.) On Linux this option also prints the state of UNIX domain sockets. ๐ง
-tโ produce terse output comprising only process identifiers (without a header), so that it is easy to use programmatically. e.g.
# reload anything using old SSL
lsof -t /lib/*/libssl.so.* | xargs -r kill -HUP
# get list of processes and then iterate over them (Bash only)
mapfile -t pids < <(
lsof -wt /var/log/your.log
)
for pid in "${pids[@]}" ; do
your_command -p "$pid"
done
The -t option implies the -w option. Literally the cleanest pipe-friendly queen out here ๐
-u sโ lists files for whichever users are in the comma-separated set s โ login names or user ID numbers, your pick. Likeabe, or548,root. (and please, no spaces in the set, bestie, it literally can't parse vibes ๐ )
Got multiple login names or UIDs? They all get smooshed into one single ORed set first, and then that set takes part in the AND option selection. Teamwork.
Now the spicy part ๐ฅ: if a login name or user ID is preceded by a ^, it becomes a negation โ meaning files of processes owned by that login name or user ID will never be listed. Periodt. A negated login name or UID selection is neither ANDed nor ORed with other selections โ it's applied before every other selection and it absolutely excludes the listing of the files of the process. So if you wanna tell lsof to leave root's files out of the chat, you go -u^root or -u^0. Bye ๐
-Uโ selects the listing of UNIX domain socket files. that's it, that's the whole vibe ๐ฆ-vโ selects the listing oflsofversion info, and it's giving receipts โจ It includes:- revision number
- when the
lsofbinary was constructed - who constructed the binary and where
- the name of the compiler used to construct the
lsofbinary - the version number of that compiler, when readily available
- the compiler and loader flags used to construct the
lsofbinary - system information, typically the output of
uname's-aoption
-Vโ tellslsofto indicate the items it was asked to list and then failed to find โ command names, file names, Internet addresses or files, login names, NFS files, PIDs, PGIDs, and UIDs. like a "hey bestie, I looked and it wasn't there" note ๐ซถ
Lowkey important caveat: when other options are ANDed to search options, or compile-time options restrict the listing of some files, lsof may not report that it failed to find a search item when an ANDed option or compile-time option prevents the listing of the open file containing the located search item.
Example time, because of course: lsof -V -iTCP@foobar -a -d 999 may not report a failure to locate open files at TCP@foobar and may not list any of them, if none have a file descriptor number of 999. A similar situation arises when HASSECURITY and HASNOSOCKSECURITY are defined at compile time and they prevent the listing of open files. ๐
+|-wโ enables (+) or disables (-) the suppression of warning messages. so+w= suppress them,-w= don't. ๐
The lsof builder may choose to have warning messages disabled or enabled by default. The default warning message state is indicated in the output of the -h or -? option. Disabling warning messages when they're already disabled, or enabling them when they're already enabled, is totally acceptable โ no judgment โจ
Also: the -t option implies the -w option.
-x [fl]โ may accompany the+dand+Doptions, and directs their processing to cross over symbolic links and|or file system mount points encountered when scanning the directory (+d) or directory tree (+D). ๐ง
If -x is specified by itself without a following parameter, cross-over processing of both symbolic links and file system mount points is enabled. Note that when -x is specified without a parameter, the next argument must begin with - or +.
The optional f parameter enables file system mount point cross-over processing; l enables symbolic link cross-over processing.
Fr fr: the-xoption may not be supplied without also supplying a+dor+Doption. It's a package deal, bestie ๐
-Xโ this one's a dialect-specific option. buckle up, it's a whole saga ๐
AIX
This IBM AIX RISC/System 6000 option requests the reporting of executed text file and shared library references.
WARNING ๐ญ: because this option uses the kernel readx() function, its use on a busy AIX system might cause an application process to hang so completely that it can neither be killed nor stopped. The author has never seen this happen or had a report of its happening, but thinks there's a remote possibility it could happen. so, uh, noted. ๐
By default use of readx() is disabled. On AIX 5L and above, lsof may need setuid-root permission to perform the actions this option requests.
The lsof builder may specify that the -X option be restricted to processes whose real UID is root. If that's been done, the -X option will not appear in the -h or -? help output unless the real UID of the lsof process is root. The default lsof distribution allows any UID to specify -X, so by default it will appear in the help output.
When AIX readx() use is disabled, lsof may not be able to report information for all text and loader file references, but it may also avoid exacerbating an AIX kernel directory search kernel error, known as the Stale Segment ID bug. ๐
The readx() function, used by lsof or any other program to access some sections of kernel virtual memory, can trigger the Stale Segment ID bug. It can cause the kernel's dir_search() function to erroneously believe that part of an in-memory copy of a file system directory has been zeroed. Another application process, distinct from lsof, asking the kernel to search the directory โ e.g., by using open(2) โ can cause dir_search() to loop forever, thus hanging the application process. not the vibe. ๐
Consult the lsof FAQ (the FAQ section gives its location) and the 00README file of the lsof distribution for a more complete description of the Stale Segment ID bug, its APAR, and methods for defining readx() use when compiling lsof.
Linux
This Linux option requests that lsof skip the reporting of information on all open TCP, UDP and UDPLITE IPv4 and IPv6 files. ๐
โโ๏ธ
It's most useful when the system has an extremely large number of open TCP, UDP and UDPLITE files, and processing their info in the /proc/net/tcp* and /proc/net/udp* files would take lsof a long time, and honestly you don't even care about that reporting.
Use this option with care and only when you're sure the information you want lsof to display isn't associated with open TCP, UDP or UDPLITE socket files. seriously, double-check. ๐
Solaris 10 and above
This Solaris 10 and above option requests the reporting of cached paths for files that have been deleted โ i.e., removed with rm(1) or unlink(2). ghost files era ๐ป
The cached path is followed by the string (deleted) to indicate that the path by which the file was opened has been deleted.
Because intervening changes made to the path โ i.e., renames with mv(1) or rename(2) โ are not recorded in the cached path, what lsof reports is only the path by which the file was opened, not its possibly different final path. so it's the origin story, not the current address ๐ฆ
-z [z]โ specifies how Solaris 10 and higher zone information is to be handled. ๐ธ
Without a following argument โ e.g., no z โ the option specifies that zone names are to be listed in the ZONE output column.
The -z option may be followed by a zone name, z. That causes lsof to list only open files for processes in that zone. Multiple -z z option and argument pairs may be specified to form a list of named zones. Any open file of any process in any of the zones will be listed, subject to other conditions specified by other options and arguments. โจ
-Z [Z]โ specifies how SELinux security contexts are to be handled. It andZfield output character support are inhibited when SELinux is disabled in the running Linux kernel. SeeOUTPUT FOR OTHER PROGRAMSfor more information on theZfield output character.
Without a following argument โ e.g., no Z โ the option specifies that security contexts are to be listed in the SECURITY-CONTEXT output column.
The -Z option may be followed by a wildcard security context name, Z. That causes lsof to list only open files for processes in that security context. Multiple -Z Z option and argument pairs may be specified to form a list of security contexts. Any open file of any process in any of the security contexts will be listed, subject to other conditions specified by other options and arguments. Note that Z can be A:B:C or *:B:C or A:B:* or *:*:C to match against the A:B:C context. wildcard slay ๐
--โ the double minus sign option is a marker that signals the end of the keyed options. ๐ฅ Use it, for example, when the first file name begins with a minus sign. It may also be used when the absence of a value for the last keyed option must be signified by the presence of a minus sign in the following option and before the start of the file names. it's the bouncer at the door of the option list ๐- names โ these are path names of specific files to list. Symbolic links are resolved before use. The first name may be separated from the preceding options with the
--option. ๐ซถ
If a name is the mounted-on directory of a file system or the device of the file system, lsof will list all the files open on the file system. To be considered a file system, the name must match a mounted-on directory name in mount(8) output, or match the name of a block device associated with a mounted-on directory name. The +|-f option may be used to force lsof to consider a name a file system identifier (+f) or a simple file (-f).
If name is a path to a directory that is not the mounted-on directory name of a file system, it's treated just as a regular file is treated โ i.e., its listing is restricted to processes that have it open as a file or as a process-specific directory, such as the root or current working directory. To request that lsof look for open files inside a directory name, use the +d s and +D D options. ๐
If a name is the base name of a family of multiplexed files โ e.g., AIX's /dev/pt[cs] โ lsof will list all the associated multiplexed files on the device that are open โ e.g., /dev/pt[cs]/1, /dev/pt[cs]/2, etc. one name, whole family, iconic ๐
okay so if a name is a UNIX domain socket name, lsof is gonna search for it by the characters of the name alone โ exactly as you specified it, and exactly as it's recorded in the kernel socket structure, periodt. (the next paragraph has the one exception to that rule, and yes bestie it's Linux.)
Specifying a relative path โ like ./file โ instead of the file's absolute path โ like /tmp/file โ will not work ๐ญ because lsof has to match the characters you specify with what it finds in the kernel UNIX domain socket structures. no cap.
If a name is a Linux UNIX domain socket name, there's one specific case where lsof is able to search for it by its device and inode number, which means name can totally be a relative path โจ. The case requires that the absolute path โ i.e., one beginning with a slash (/) โ be used by the process that created the socket, and hence be stored in the /proc/net/unix file; and it requires that lsof be able to obtain the device and node numbers of both the absolute path in /proc/net/unix and name via successful stat(2) system calls. When those conditions are met, lsof will be able to search for the UNIX domain socket when some path to it is specified in name ๐ซถ. So for example, if the path is /dev/log, and an lsof search is initiated when the working directory is /dev, then name could be ./log. slay.
If a name is none of the above, lsof will list any open files whose device and inode match that of the specified path name ๐ .
If you have also specified the -b option, the only names you may safely specify are file systems for which your mount table supplies alternate device numbers. See the AVOIDING KERNEL BLOCKS and ALTERNATE DEVICE NUMBERS sections for more info ๐.
Multiple file names are joined in a single ORed set before participating in AND option selection.
โจ AFS โจ
Lsof supports the recognition of AFS files for these dialects (and AFS versions):
AIX 4.1.4 (AFS 3.4a)
HP-UX 9.0.5 (AFS 3.4a)
Linux 1.2.13 (AFS 3.3)
Solaris 2.[56] (AFS 3.4a)
It may recognize AFS files on other versions of these dialects, but has not been tested there ngl. Depending on how AFS is implemented, lsof may recognize AFS files in other dialects, or may have difficulties recognizing AFS files in the supported dialects ๐ฆ.
Lsof may have trouble identifying all aspects of AFS files in supported dialects when AFS kernel support is implemented via dynamic modules whose addresses do not appear in the kernel's variable name list. In that case, lsof may have to guess at the identity of AFS files, and might not be able to obtain volume info from the kernel that's needed for calculating AFS volume node numbers ๐. When lsof can't compute volume node numbers, it reports blank in the NODE column.
The -A A option is available in some dialect implementations of lsof for specifying the name list file where dynamic module kernel addresses may be found. When this option is available, it will be listed in the lsof help output, presented in response to the -h or -?.
See the lsof FAQ (the FAQ section gives its location) for more info about dynamic modules, their symbols, and how they affect lsof options.
Because AFS path lookups don't seem to participate in the kernel's name cache operations, lsof can't identify path name components for AFS files ๐.
๐ SECURITY ๐
Lsof has three features that may cause security concerns, and we're gonna go through them one by one because this is important, bestie:
First, its default compilation mode allows anyone to list all open files with it. Second, by default it creates a user-readable and user-writable device cache file in the home directory of the real user ID that executes lsof. (The list-all-open-files and device cache features may be disabled when lsof is compiled.) Third, its -k and -m options name alternate kernel name list or memory files.
Restricting the listing of all open files is controlled by the compile-time HASSECURITY and HASNOSOCKSECURITY options. When HASSECURITY is defined, lsof will allow only the root user to list all open files. The non-root user may list only open files of processes with the same user IDentification number as the real user ID number of the lsof process (the one that its user logged on with).
However, if HASSECURITY and HASNOSOCKSECURITY are both defined, anyone may list open socket files, provided they are selected with the -i option ๐.
When HASSECURITY is not defined, anyone may list all open files.
Help output, presented in response to the -h or -? option, gives the status of the HASSECURITY and HASNOSOCKSECURITY definitions.
See the Security section of the 00README file of the lsof distribution for info on building lsof with the HASSECURITY and HASNOSOCKSECURITY options enabled.
Creation and use of a user-readable and user-writable device cache file is controlled by the compile-time HASDCACHE option. See the DEVICE CACHE FILE section and the sections that follow it for details on how its path is formed. For security considerations it's important to note that in the default lsof distribution, if the real user ID under which lsof is executed is root, the device cache file will be written in root's home directory โ e.g., / or /root ๐. When HASDCACHE is not defined, lsof does not write or attempt to read a device cache file.
When HASDCACHE is defined, the lsof help output, presented in response to the -h, -D?, or -? options, will provide device cache file handling info. When HASDCACHE is not defined, the -h or -? output will have no -D option description.
Before you decide to disable the device cache file feature โ enabling it improves the performance of lsof by reducing the startup overhead of examining all the nodes in /dev (or /devices) โ read the discussion of it in the 00DCACHE file of the lsof distribution and the lsof FAQ (the FAQ section gives its location) ๐ง.
WHEN IN DOUBT, YOU CAN TEMPORARILY DISABLE THE USE OF THE DEVICE CACHE FILE WITH THE -Di OPTION.
When lsof user declares alternate kernel name list or memory files with the -k and -m options, lsof checks the user's authority to read them with access(2). This is intended to prevent whatever special power lsof's modes might confer on it from letting it read files not normally accessible via the authority of the real user ID โญ.
๐ OUTPUT ๐
This section describes the info lsof lists for each open file. See the OUTPUT FOR OTHER PROGRAMS section for additional info on output that can be processed by another program.
Lsof only outputs printable (declared so by isprint(3)) 8 bit characters. Non-printable characters are printed in one of three forms: the C \[bfrnt] form; the control character ^ form (e.g., ^@); or hexadecimal leading \x form (e.g., \xab). Space is non-printable in the COMMAND column (\x20) and printable elsewhere ๐
For some dialects โ if HASSETLOCALE is defined in the dialect's machine.h header file โ lsof will print the extended 8 bit characters of a language locale. The lsof process must be supplied a language locale environment variable (e.g., LANG) whose value represents a known language locale in which the extended characters are considered printable by isprint(3). Otherwise lsof considers the extended characters non-printable and prints them according to its rules for non-printable characters, stated above. Consult your dialect's setlocale(3) man page for the names of other environment variables that may be used in place of LANG โ e.g., LC_ALL, LC_CTYPE, etc.
Lsof's language locale support for a dialect also covers wide characters โ e.g., UTF-8 โ when HASSETLOCALE and HASWIDECHAR are defined in the dialect's machine.h header file, and when a suitable language locale has been defined in the appropriate environment variable for the lsof process ๐ธ. Wide characters are printable under those conditions if iswprint(3) reports them to be. If HASSETLOCALE, HASWIDECHAR and a suitable language locale aren't defined, or if iswprint(3) reports wide characters that aren't printable, lsof considers the wide characters non-printable and prints each of their 8 bits according to its rules for non-printable characters, stated above.
Consult the answers to the "Language locale support" questions in the lsof FAQ (the FAQ section gives its location) for more info.
Lsof dynamically sizes the output columns each time it runs, guaranteeing that each column is a minimum size โจ. It also guarantees that each column is separated from its predecessor by at least one space.
COMMAND ๐ฌ
contains the first nine characters of the name of the UNIX command associated with the process. If a non-zero w value is specified to the +c w option, the column contains the first w characters of the name of the UNIX command associated with the process up to the limit of characters supplied to lsof by the UNIX dialect. (See the description of the +c w command or the lsof FAQ for more info. The FAQ section gives its location.)
If w is less than the length of the column title, COMMAND, it will be raised to that length.
If a zero w value is specified to the +c w option, the column contains all the characters of the name of the UNIX command associated with the process ๐
.
All command name characters maintained by the kernel in its structures are displayed in field output when the command name descriptor (c) is specified. See the OUTPUT FOR OTHER COMMANDS section for info on selecting field output and the associated command name descriptor.
PID ๐
is the Process IDentification number of the process.
TID ๐งต
is the task (thread) IDentification number, if task (thread) reporting is supported by the dialect and a task (thread) is being listed. (If help output โ i.e., the output of the -h or -? options โ shows this option, then task (thread) reporting is supported by the dialect.)
A blank TID column in Linux indicates a process โ i.e., a non-task.
TASKCMD ๐ท๏ธ
is the task command name. Generally this will be the same as the process named in the COMMAND column, but some task implementations (e.g., Linux) permit a task to change its command name ๐.
The TASKCMD column width is subject to the same size limitation as the COMMAND column.
ZONE ๐
is the Solaris 10 and higher zone name. This column must be selected with the -z option.
SECURITY-CONTEXTโ this one's the SELinux security context, bestie. ๐ก๏ธ You have to select this column with the-Zoption, no skipping. And lowkey important:-Zgets inhibited when SELinux is disabled in the running Linux kernel, so if you're getting nothing, check that first. ๐ญPPIDโ the Parent Process IDentification number of the process. Only shows up when you've specified the-Roption. ๐PGIDโ the process group IDentification number associated with the process. Only shows up when you've specified the-goption. ๐USERโ the user ID number or login name of the user the process belongs to, usually the same as whatps(1)reports. But โ and this is the tea โ โ on Linux,USERis the user ID number or login that owns the directory in/procwherelsoffinds info about the process. Usually that's the same valueps(1)reports, but it may differ when the process has changed its effective user ID. (Peep the-loption description for when a user ID number vs. a login name gets displayed.) ๐ซถFDโ the File Descriptor number of the file, or one of these iconic little codes:
cwd current working directory;
Lnn library references (AIX);
ctty character tty;
DEL deleted file;
err FD information error (see NAME column);
fp. Fileport (Darwin);
jld jail directory (FreeBSD);
ltx shared library text (code and data);
Mxx hex memory-mapped type number xx.
m86 DOS Merge mapped file;
mem memory-mapped file;
mmap memory-mapped device;
NOFD for a Linux /proc/<PID>/fd directory that can't be opened --
the directory path appears in the NAME column, followed by an error
message;
pd parent directory;
Rnn unknown pregion number (HP-UX);
rtd root directory;
twd per task current working directory;
txt program text (code and data);
v86 VP/ix mapped file;
Okay so FD is followed by one of these characters, and it's describing the mode the file is open under, slay:
r for read access;
w for write access;
u for read and write access;
space if mode unknown and no lock
character follows;
`-' if mode unknown and lock
character follows.
Then the mode character is followed by one of these lock characters, describing the type of lock on the file โ the drama continues:
N for a Solaris NFS lock of unknown type;
r for read lock on part of the file;
R for a read lock on the entire file;
w for a write lock on part of the file;
W for a write lock on the entire file;
u for a read and write lock of any length;
U for a lock of unknown type;
x for an SCO OpenServer Xenix lock on part of the file;
X for an SCO OpenServer Xenix lock on the entire file;
space if there is no lock.
Head to the LOCKS section if you want the full lore on that lock information character. ๐
The FD column contents constitute a single field for parsing in post-processing scripts โ so don't go splitting it, bestie. And FD numbers bigger than 9999 get abbreviated to a `*' followed by the last three digits. E.g., 10001 appears as `*001'. Not me finding that cursed but also kind of cute. ๐ญ
โจ TYPE โจ
TYPE is the type of the node associated with the file โ e.g., VDIR, VREG, etc.
Or, like, literally one of these hundred-ish options, no cap:
`ax25'for a Linux AX.25 socket;`a_inode'for anonymous inode;`icmp'for an ICMP socket;`inet'for an Internet domain socket;`ipx'for an IPX socket;`key'for an internal key management socket;`lla'for a HP-UX link level access file;`ndrv'for a net driver socket;`netlink'for a netlink socket;`pack'for a packet socket;`ppp'for a PPP socket;`raw'for a raw socket;`raw6'for a raw IPv6 socket;`rte'for an AF_ROUTE socket;`sock'for a socket of unknown domain;`systm'for a system socket;`unix'for a UNIX domain socket;`x.25'for an HP-UX x.25 socket;`ATALK'for an AppleTalk socket;`BLK'for a block special file;`CHR'for a character special file;`DEL'for a Linux map file that has been deleted;`DIR'for a directory;`DOOR'for a VDOOR file;`EVENTFD'for an eventfd;`FIFO'for a FIFO special file;`FSEVENTS'for fsevents;`IPv4'for an IPv4 socket;`IPv6'for an open IPv6 network file โ even if its address is IPv4, mapped in an IPv6 address;`KQUEUE'for a BSD style kernel event queue file;`LINK'for a symbolic link file;`MPB'for a multiplexed block file;`MPC'for a multiplexed character file;`PAS'for a/proc/asfile;`PAXV'for a/proc/auxvfile;`PCRE'for a/proc/credfile;`PCTL'for a/proccontrol file;`PCUR'for the current/procprocess;`PCWD'for a/proccurrent working directory;`PDIR'for a/procdirectory;`PETY'for a/procexecutable type (etype);`PFD'for a/procfile descriptor;`PFDR'for a/procfile descriptor directory;`PFIL'for an executable/procfile;`PFPR'for a/procFP register set;`PGD'for a/proc/pagedatafile;`PGID'for a/procgroup notifier file;`PIPE'for pipes;`PLC'for a/proc/lwpctlfile;`PLDR'for a/proc/lpwdirectory;`PLDT'for a/proc/ldtfile;`PLPI'for a/proc/lpsinfofile;`PLST'for a/proc/lstatusfile;`PLU'for a/proc/lusagefile;`PLWG'for a/proc/gwindowsfile;`PLWI'for a/proc/lwpsinfofile;`PLWS'for a/proc/lwpstatusfile;`PLWU'for a/proc/lwpusagefile;`PLWX'for a/proc/xregsfile;`PMAP'for a/procmap file (map);`PMPS'for a/proc/mapsfile;`PMEM'for a/procmemory image file;`PNTF'for a/procprocess notifier file;`POBJ'for a/proc/objectfile;`PODR'for a/proc/objectdirectory;`POLP'for an old format/proclight weight process file;`POPF'for an old format/procPID file;`POPG'for an old format/procpage data file;`PORT'for a SYSV named pipe;`PREG'for a/procregister file;`PRMP'for a/proc/rmapfile;`PROCDSC'for a processor descriptor;`PRTD'for a/procroot directory;`PSGA'for a/proc/sigactfile;`PSIN'for a/proc/psinfofile;`PSTA'for a/procstatus file;`PSXMQ'for a POSIX message queue file;`PSXSEM'for a POSIX semaphore file;`PSXSHM'for a POSIX shared memory file;`PTS'for a/dev/ptsfile;`PUSG'for a/proc/usagefile;`PW'for a/proc/watchfile;`PXMP'for a/proc/xmapfile;`REG'for a regular file;`SHM'for a shared memory file;`SMT'for a shared memory transport file;`STR'for streams;`STSO'for a stream socket;`UNKN'for an unknown file;`UNKNcwd'for unknown current working directory;`UNKNdel'for unknown deleted file;`UNKNfd'for unknown file descriptor;`UNKNmem'for unknown memory-mapped file;`UNKNrtd'for unknown root directory;`UNKNtxt'for unknown program text;`UNNM'for an unnamed type file;`XNAM'for an OpenServer Xenix special file of unknown type;`XSEM'for an OpenServer Xenix semaphore file;`XSD'for an OpenServer Xenix shared data file;`NPOLICY'for Darwin network policy;`UNSP'for an unsupported file;
โฆor, if the corresponding name isn't known, you just get the four type number octets. The mystery era. ๐ต๏ธโโ๏ธ
FILE-ADDRโ holds the kernel file structure address whenfhas been specified to+f. ๐FCTโ holds the file reference count from the kernel file structure whenchas been specified to+f. ๐ขFILE-FLAGโ whengorGhas been specified to+f, this field holds the contents of thef_flag[s]member of the kernel file structure and the kernel's per-process open file flags (if available).Gmakes them display in hexadecimal;ggives you short-hand names instead. Two lists may be displayed, with entries separated by commas, and the lists separated by a semicolon (`;'). The first list may contain short-hand names forf_flag[s]values from the following table: ๐
โฆand the list just keeps going, bestie, because of course it does ๐ here's the rest of the flag shorthand:
AIOโ asynchronous I/O (e.g., FAIO)APโ appendASYNโ asynchronous I/O (e.g., FASYNC)BASโ block, test, and set in useBKIUโ block if in useBLโ use block offsetsBSKโ block seekCAโ copy avoidCIOโ concurrent I/OCLONโ cloneCLRDโ CL readCRโ createDFโ deferDFIโ defer INDDFLUโ data flushDIRโ directDLYโ delayDOCLโ do cloneDSYNโ data-only integrityDTYโ must be a directoryEVOโ event onlyEXโ open for execEXCLโ exclusive openFSYNโ synchronous writesGCDFโ defer duringunp_gc()(AIX)GCMKโ mark duringunp_gc()(AIX)GTTYโ accessed via/dev/ttyHUPโ HUP in progressKERNโ kernelKIOCโ kernel-issued ioctlLCKโ has lockLGโ large fileMBLKโ stream message blockMKโ markMNTโ mountMSYNโ multiplex synchronizationNATMโ don't update atimeNBโ non-blocking I/ONBDRโ no BDRM checkNBIOโ SYSV non-blocking I/ONBFโ n-buffering in effectNCโ no cacheNDโ no delayNDSYโ no data synchronizationNETโ networkNFLKโ don't follow linksNMFSโ NM file systemNOTOโ disable background stopNSHโ no shareNTTYโ no controlling TTYOLRMโ OLR mirrorPAIOโ POSIX asynchronous I/OPATHโ pathPPโ POSIX pipeRโ readRCโ file and record locking cacheREVโ revokedRSHโ shared readRSYNโ read synchronizationRWโ read and write accessSLโ shared lockSNAPโ cooked snapshotSOCKโ socketSQSHโ Sequent shared set on openSQSVโ Sequent SVM set on openSQRโ Sequent set repair on openSQS1โ Sequent full shared openSQS2โ Sequent partial shared openSTPIโ stop I/OSWRโ synchronous readSYNโ file integrity while writingTCPMโ avoid TCP collisionTMPFโ temporary fileTRโ truncateWโ writeWKUPโ parallel I/O synchronizationWTGโ parallel I/O synchronizationVHโ vhangup pendingVTXTโ virtual textXLโ exclusive lock
Ok so this whole list of names was derived from F* #define's in dialect header files <fcntl.h>, <linux</fs.h>, <sys/fcntl.c>, <sys/fcntlcom.h>, and <sys/file.h> โ and yeah, that <linux</fs.h> weirdness is literally in the original, don't @ me ๐ go check the common.h header file if you want to see the full correspondence between those short-hand names up there and the header file definitions. iykyk ๐ซถ
And then โ plot twist โ the second list (the one after the semicolon) might contain short-hand names for kernel per-process open file flags, and those come from this table:
ALLCโ allocatedBRโ the file has been readBHUPโ activity stopped bySIGHUPBWโ the file has been writtenCLSGโ closingCXโ close-on-exec (seefcntl(F_SETFD))LCKโ lock was appliedMPโ memory-mappedOPIPโ open pending - in progressRSVWโ reserved waitSHMTโUF_FSHMATset (AIX)USEโ in use (multi-threaded)
๐ธ NODE-ID ๐ธ
(or INODE-ADDR for some dialects!) contains a unique identifier for the file node โ usually the kernel vnode or inode address, but also occasionally a concatenation of device and node number โ when n has been specified to +f โจ
๐ฆ DEVICE ๐ฆ
contains the device numbers, separated by commas, for a character special, block special, regular, directory or NFS file;
or memory for a memory file system node under Tru64 UNIX;
or the address of the private data area of a Solaris socket stream;
or a kernel reference address that identifies the file (the kernel reference address may be used for FIFO's, for example.);
or the base address or device name of a Linux AX.25 socket device.
Usually only the lower thirty two bits of Tru64 UNIX kernel addresses are displayed ๐
๐ SIZE, SIZE/OFF, or OFFSET ๐
is the size of the file or the file offset in bytes. A value shows up in this column only if it's actually available. lsof displays whatever value โ size or offset โ is appropriate for the type of the file and the version of lsof.
On some UNIX dialects lsof can't obtain accurate or consistent file offset information from its kernel data sources, sometimes just for particular kinds of files (e.g., socket files.) In other cases, files don't have true sizes โ e.g., sockets, FIFOs, pipes โ so lsof displays for their sizes the content amounts it finds in their kernel buffer descriptors (e.g., socket buffer size counts or TCP/IP window sizes.) Consult the lsof FAQ (the FAQ section gives its location) for more info, bestie ๐
The file size is displayed in decimal; the offset is normally displayed in decimal with a leading 0t if it contains 8 digits or less; in hexadecimal with a leading 0x if it's longer than 8 digits. (Consult the -o o option description for info on when 8 might default to some other value.)
So basically the leading 0t and 0x are how you tell an offset apart when the column could contain both a size and an offset (i.e., its title is SIZE/OFF) ๐ฅ
If the -o option is specified, lsof always displays the file offset (or nothing if no offset is available) and labels the column OFFSET. The offset always begins with 0t or 0x as described above.
You, the lsof user, can control the switch from 0t to 0x with the -o o option. Consult its description for more info ๐
If the -s option is specified, lsof always displays the file size (or nothing if no size is available) and labels the column SIZE. The -o and -s options are mutually exclusive โ they can't both be specified ๐ญ
If the -H option is specified, lsof displays file size in human readable form ๐ซถ
For files that don't have a fixed size โ e.g., don't reside on a disk device โ lsof will display appropriate information about the current size or position of the file if it's available in the kernel structures that define the file.
๐ NLINK ๐
contains the file link count when +L has been specified;
โญ NODE โญ
is the node number of a local file;
or the inode number of an NFS file in the server host;
or the Internet protocol type โ e.g, TCP;
or STR for a stream;
or CCITT for an HP-UX x.25 socket;
or the IRQ or inode number of a Linux AX.25 socket device.
๐ NAME ๐
is the name of the mount point and file system on which the file resides;
or the name of a file specified in the names option (after any symbolic links have been resolved);
or the name of a character special or block special device;
or the local and remote Internet addresses of a network file โ the local host name or IP number is followed by a colon (:), the port, ->, and the two-part remote address; IP addresses may be reported as numbers or names, depending on the +|-M, -n, and -P options; colon-separated IPv6 numbers are enclosed in square brackets; IPv4 INADDR_ANY and IPv6 IN6_IS_ADDR_UNSPECIFIED addresses, and zero port numbers are represented by an asterisk (*); a UDP destination address may be followed by the amount of time elapsed since the last packet was sent to the destination; TCP, UDP and UDPLITE remote addresses may be followed by TCP/TPI information in parentheses โ state (e.g., (ESTABLISHED), (Unbound)), queue sizes, and window sizes (not all dialects) โ in a fashion similar to what netstat(1) reports; see the -T option description or the description of the TCP/TPI field in OUTPUT FOR OTHER PROGRAMS for more info on state, queue size, and window size;
or the address or name of a UNIX domain socket, possibly including a stream clone device name, a file system object's path name, local and foreign kernel addresses, socket pair information, and a bound vnode address;
or the local and remote mount point names of an NFS file;
or STR, followed by the stream name;
or a stream character device name, followed by -> and the stream name or a list of stream module names, separated by ->;
or STR: followed by the SCO OpenServer stream device and module names, separated by ->;
or system directory name, --, and as many components of the path name as lsof can find in the kernel's name cache for selected dialects (see the KERNEL NAME CACHE section for more info.) ๐ง
PIPE->followed by the destination address of a Solaris kernel pipe โ yes, an actual address, we're getting into the weeds and I love it here ๐ซถCOMMON:followed by the device name from the vnode device information structure โ this one's for a Solaris common vnode, iykyk- the address family, then a slash (
/), then fourteen comma-separated bytes of a non-Internet raw socket address โ count them, bestie, fourteen, not thirteen, not fifteen ๐ - the HP-UX x.25 local address, then the virtual connection number (if there is one), then the remote address (if there is one) โ lots of ifs in there, that's just how x.25 rolls
(dead)for disassociated Tru64 UNIX files โ typically terminal files that got flagged with theTIOCNOTTYioctl and then closed by daemons ๐ญ rip little terminalrd=<offset>andwr=<offset>for the read and write offsets of a FIFO โ offsets, plural, both of them, don't forget the write oneclone n:/dev/eventfor SCO OpenServer file clones of the/dev/eventdevice, where n is the minor device number of the file โ iconic clone behaviour, honestly(socketpair: n)for a Solaris 2.6, 8, 9 or 10 UNIX domain socket created by thesocketpair(3N)network function โ and yes it's 2.6, 8, 9 or 10, that's the exact list, no 7 in sight, don't ask ๐no PCBfor socket files that don't have a protocol block attached to them โ optionally followed by, CANTSENDMOREif sending on the socket has been disabled, or, CANTRCVMOREif receiving has been disabled (like, say, by theshutdown(2)function) ๐- the local and remote addresses of a Linux IPX socket file, in the form
<net>:[<node>:]<port>, followed in parentheses by the transmit and receive queue sizes, and the connection state โ a whole little info-dump in one column, slay dgramorstreamfor the type of UnixWare 7.1.1 and above in-kernel UNIX domain sockets, followed by a colon (:) and the local path name when it's available, followed by->and the remote path name or kernel socket address in hexadecimal when it's available โ so many *when it's available*s, the kernel is shy sometimes- the association value, association index, endpoint value, local address, local port, remote address and remote port for Linux SCTP sockets โ that's seven things, in order, in one column, which is genuinely a lot of main character energy for one column โญ
protocol:followed by the Linux socket's protocol attribute โ short, sweet, to the point
For dialects that support a namefs file system โ the one that lets one file be attached to another with fattach(3C) โ lsof will add (FA:<address1><direction><address2>) to the NAME column. So: <address1> and <address2> are hexadecimal vnode addresses. <direction> will be <- if <address2> has been fattach'ed to this vnode whose address is <address1>; and -> if <address1>, the vnode address of this vnode, has been fattach'ed to <address2>. And <address1> may be omitted if it already shows up in the DEVICE column โ no need to say it twice, we're not that kind of program ๐
lsof may also add two parenthetical notes to the NAME column for open Solaris 10 files: (?) if lsof considers the path name of questionable accuracy; and (deleted) if the -X option has been specified and lsof detects the open file's path name has been deleted. Consult the lsof FAQ (the FAQ section gives its location) for more on these NAME column additions โ they wrote the whole thing up, go read it ๐ฆ
๐ LOCKS ๐
Okay so here's the tea: lsof can't adequately report the wide variety of UNIX dialect file locks in a single character. One character. That's the constraint. What it reports in that single character is a compromise between what it actually finds in the kernel and the limitations of the reporting format โ and honestly? Respect for trying at all ๐
Also, when a process holds several byte level locks on a file, lsof only reports the status of the first lock it encounters. And if that one is a byte level lock, then the lock character gets reported in lower case โ i.e., r, w, or x โ rather than the upper case equivalent that gets reported for a full file lock. Lowercase = byte level, uppercase = whole file, that's the code, don't forget it ๐ฅ
Generally lsof can only report on locks held by local processes on local files. When a local process sets a lock on a remotely mounted (e.g., NFS) file, the remote server host usually records the lock state โ so it's not in your local kernel, and lsof can't see it. There is one exception, and of course it's Solaris: at some patch levels of 2.3, and in all versions above 2.4, the Solaris kernel records information on remote locks in local structures. Noted, filed away, iconic of Solaris ngl ๐ซ
lsof also has trouble reporting locks for some UNIX dialects. Consult the BUGS section of this manual page or the lsof FAQ (the FAQ section gives its location) for more information โ yeah, there's a whole section of things that don't quite work, we'll get there ๐ญ
๐ OUTPUT FOR OTHER PROGRAMS ๐
Okay bestie, so when you use the -F option, lsof switches into full โfeed me to another programโ mode โ the output is literally suitable for processing by another program, like an awk or Perl script, or a C program. ๐
Each unit of information gets output in a field thatโs identified with a leading character and terminated by a NL (012) โ or a NUL (000) if the 0 (zero) field identifier character is specified. The data of the field follows immediately after the field identification character and extends to the field terminator. โจ
Itโs possible to think of field output as process and file sets. A process set begins with a field whose identifier is p โ thatโs the process IDentifier (PID) field. It extends to the beginning of the next PID field or the beginning of the first file set of the process, whichever comes first. Included in the process set are fields that identify the command, the process group IDentification (PGID) number, the task (thread) ID (TID), and the user ID (UID) number or login name.
A file set begins with a field whose identifier is f โ thatโs the file descriptor field. Itโs followed by lines that describe the fileโs access mode, lock state, type, device, size, offset, inode, protocol, name and stream module names. It extends to the beginning of the next file or process set, whichever comes first.
When the NUL (000) field terminator has been selected with the 0 (zero) field identifier character, lsof ends each process and file set with a NL (012) character.
Lsof always produces one field: the PID (p) field. In repeat mode, the marker (m) is also produced. All other fields may be declared optionally in the field identifier character list that follows the -F option. When a field selection character identifies an item lsof does not normally list โ e.g., PPID, selected with -R โ specification of the field character โ e.g., -FR โ also selects the listing of the item. No cap.
Lsof version from 4.88 to 4.93.2 always produced one more field, the file descriptor (f) field. However, lsof in this version doesnโt produce it. This change is for supporting the use case that a user needs only the PID field, and doesnโt need the file descriptor field. Specify f explicitly if you need the field.
It is entirely possible to select a set of fields that cannot easily be parsed โ e.g., if the field descriptor field is not selected, it may be difficult to identify file sets. To help you avoid this difficulty, lsof supports the -F option; it selects the output of all fields with NL terminators (the -F0 option pair selects the output of all fields with NUL terminators). For compatibility reasons neither -F nor -F0 select the raw device field.
These are the fields that lsof will produce. The single character listed first is the field identifier. ๐ซถ
aโ file access modecโ process command name (all characters from proc or user structure)Cโ file structure share countdโ fileโs device character codeDโ fileโs major/minor device number (0x<hexadecimal>)fโ file descriptorFโ file structure address (0x<hexadecimal>)Gโ file flaGs (0x<hexadecimal>; names if+fgfollows)gโ process group IDiโ fileโs inode numberKโ tasK IDkโ link countlโ fileโs lock statusLโ process login namemโ marker between repeated output (always selected in repeat mode)Mโ the task comMand namenโ file name, comment, Internet addressNโ node identifier (ox<hexadecimal>oโ fileโs offset (0t<decimal>or0x<hexadecimal>, see-o o)pโ process ID (always selected)Pโ protocol namerโ raw device number (0x<hexadecimal>)Rโ parent process IDsโ fileโs size (decimal)Sโ fileโs stream identificationtโ fileโs typeTโ TCP/TPI information, identified by prefixes (the=is part of the prefix):QR=<read queue size>QS=<send queue size>SO=<socket options and values>(not all dialects)SS=<socket states>(not all dialects)ST=<connection state>TF=<TCP flags and values>(not all dialects)WR=<window read size>(not all dialects)WW=<window write size>(not all dialects)
uโ process user IDzโ Solaris 10 and higher zone nameZโ SELinux security context (inhibited when SELinux is disabled)0โ use NUL field terminator character in place of NL1-9โ dialect-specific field identifiers (The output of-F?identifies the information to be found in dialect-specific fields.)
(TCP/TPI information isnโt reported for all supported UNIX dialects. The -h or -? help output for the -T option will show what TCP/TPI reporting can be requested.)
You can get on-line help information on these characters and their descriptions by specifying the -F? option pair. (Escape the ? character as your shell requires.) Additional information on field content can be found in the OUTPUT section.
As an example, -F pcfn will select the process ID (p), command name (c), file descriptor (f) and file name (n) fields with an NL field terminator character; -F pcfn0 selects the same output with a NUL (000) field terminator character.
Lsof doesnโt produce all fields for every process or file set โ only those that are available. Some fields are mutually exclusive: file device characters and file major/minor device numbers; file inode number and protocol name; file name and stream identification; file size and offset. One or the other member of these mutually exclusive sets will appear in field output, but not both. ๐
Normally lsof ends each field with a NL (012) character. The 0 (zero) field identifier character may be specified to change the field terminator character to a NUL (000). A NUL terminator may be easier to process with xargs (1), for example, or with programs whose quoting mechanisms may not easily cope with the range of characters in the field output. When the NUL field terminator is in use, lsof ends each process and file set with a NL (012).
Three aids to producing programs that can process lsof field output are included in the lsof distribution. ๐
- The first is a C header file,
lsof_fields.h, that contains symbols for the field identification characters, indexes for storing them in a table, and explanation strings that may be compiled into programs. Lsof uses this header file. - The second aid is a set of sample scripts that process field output, written in awk, Perl 4, and Perl 5. Theyโre located in the
scriptssubdirectory of the lsof distribution. - The third aid is the C library used for the lsof test suite. The test suite is written in C and uses field output to validate the correct operation of lsof. The library can be found in the
tests/LTlib.cfile of the lsof distribution. The library uses the first aid, thelsof_fields.hheader file.
โณ BLOCKS AND TIMEOUTS โณ
Lsof can be blocked by some kernel functions that it uses โ lstat(2), readlink(2), and stat(2). These functions are stalled in the kernel, for example, when the hosts where mounted NFS file systems reside become inaccessible. ๐ญ
Lsof attempts to break these blocks with timers and child processes, but the techniques are not wholly reliable. When lsof does manage to break a block, it will report the break with an error message. The messages may be suppressed with the -t and -w options.
The default timeout value may be displayed with the -h or -? option, and it may be changed with the -S [t] option. The minimum for t is two seconds, but you should avoid small values, since slow system responsiveness can cause short timeouts to expire unexpectedly and perhaps stop lsof before it can produce any output.
When lsof has to break a block during its access of mounted file system information, it normally continues, although with less information available to display about open files.
Lsof can also be directed to avoid the protection of timers and child processes when using the kernel functions that might block by specifying the -O option. While this will allow lsof to start up with less overhead, it exposes lsof completely to the kernel situations that might block it. Use this option cautiously. ๐ฅ
๐ก๏ธ AVOIDING KERNEL BLOCKS ๐ก๏ธ
You can use the -b option to tell lsof to avoid using kernel functions that would block. Some cautions apply, bestie. ๐ซถ
First, using this option usually requires that your system supply alternate device numbers in place of the device numbers that lsof would normally obtain with the lstat(2) and stat(2) kernel functions. See the ALTERNATE DEVICE NUMBERS section for more information on alternate device numbers.
Second, you canโt specify names for lsof to locate unless theyโre file system names. This is because lsof needs to know the device and inode numbers of files listed with names in the lsof options, and the -b option prevents lsof from obtaining them. Moreover, since lsof only has device numbers for the file systems that have alternates, its ability to locate files on file systems depends completely on the availability and accuracy of the alternates. If no alternates are available, or if theyโre incorrect, lsof wonโt be able to locate files on the named file systems.
Third, if the names of your file system directories that lsof obtains from your systemโs mount table are symbolic links, lsof wonโt be able to resolve the links. This is because the -b option causes lsof to avoid the kernel readlink(2) function it uses to resolve symbolic links.
Finally, using the -b option causes lsof to issue warning messages when it needs to use the kernel functions that the -b option directs it to avoid. You can suppress these messages by specifying the -w option, but if you do, you wonโt see the alternate device numbers reported in the warning messages. ๐
๐ ALTERNATE DEVICE NUMBERS ๐
So sometimes your girl can't get the info the normal way. On some dialects, when lsof has to break a block because it can't get information about a mounted file system via the lstat(2) and stat(2) kernel functions, or because you specified the -b option, lsof can pull some of what it needs โ the device number and possibly the file system type โ from the system mount table. And when that's possible, lsof will report the device number it obtained. (You can suppress the report by specifying the -w option, if you're not into it.)
You can absolutely help this process along ๐
if your mount table is supported with an /etc/mtab or /etc/mnttab file that contains an options field โ just add a ``dev=xxxx'' field for mount points that don't already have one in their options strings.
Heads up bestie: you must be able to edit the file. Some mount tables like recent Solaris/etc/mnttabor Linux/proc/mountsare read-only and can't be modified. Tragic, I know. ๐ญ
You may also be able to supply device numbers using the +m and +m m options, provided they're supported by your dialect. Check the output of lsof's -h or -? options to see if the +m and +m m options are available.
The ``xxxx'' portion of the field is the hexadecimal value of the file system's device number. (Consult the st_dev field of the output of the lstat(2) and stat(2) functions for the appropriate values for your file systems.) Here's an example from a Sun Solaris 2.6 /etc/mnttab for a file system remotely mounted via NFS:
nfs ignore,noquota,dev=2a40001
There's a genuine advantage to having ``dev=xxxx'' entries in your mount table file, especially for file systems mounted from remote NFS servers. Scenario: when a remote server crashes and you want to identify its users by running lsof on one of its clients, lsof probably won't be able to get output from the lstat(2) and stat(2) functions for the file system. But if it can obtain the file system's device number from the mount table, it will be able to display the files open on the crashed NFS server. Iconic behavior honestly. ๐
Some dialects that don't use an ASCII /etc/mtab or /etc/mnttab file for the mount table may still provide an alternative device number in their internal mount tables. This includes:
AIXApple DarwinFreeBSDNetBSDOpenBSDTru64 UNIX
Lsof knows how to obtain the alternative device number for these dialects and uses it when its attempt to lstat(2) or stat(2) the file system is blocked. It's giving resourceful. โจ
Not sure if your dialect supplies alternate device numbers for file systems from its mount table? Run this lsof incantation to see if it reports any alternate device numbers:
lsof -b
Look for standard error file warning messages that begin ``assuming "dev=xxxx" from ...''. That's your signal, iykyk. ๐ฆ
๐ง KERNEL NAME CACHE ๐ง
Lsof is able to examine the kernel's name cache โ or use other kernel facilities (e.g., the ADVFS 4.x tag_to_path() function under Tru64 UNIX) โ on some dialects for most file system types, excluding AFS, and extract recently used path name components from it. (Quick note: AFS file system path lookups don't use the kernel's name cache, and some Solaris VxFS file system operations apparently don't use it either. Rude of them.)
Lsof reports the complete paths it finds in the NAME column. But if it can't report all the components in a path, it reports in the NAME column the file system name, followed by a space, two - characters, another space, and the name components it has located, separated by the / character.
When lsof is run in repeat mode โ i.e., with the -r option specified โ the extent to which it can report path name components for the same file may vary from cycle to cycle. Why? Because other running processes can cause the kernel to remove entries from its name cache and replace them with others. Chaos, honestly. ๐ช๏ธ
Real talk warning: lsof's use of the kernel name cache to identify the paths of files can lead it to report incorrect components under some circumstances. This can happen when the kernel name cache uses device and node number as a key (e.g., SCO OpenServer) and a key on a rapidly changing file system is reused. If the UNIX dialect's kernel doesn't purge the name cache entry for a file when it is unlinked, lsof may find a reference to the wrong entry in the cache. The lsof FAQ (The FAQ section gives its location.) has more information on this situation. ๐
Lsof can report path name components for these dialects:
FreeBSDHP-UXLinuxNetBSDSCO OpenServerSCO|Caldera UnixWareSolarisTru64 UNIX
Lsof can't report path name components for these dialects:
AIXOpenBSD
If you want to know why lsof can't report path name components for some dialects, see the lsof FAQ (The FAQ section gives its location.) ๐ซถ
๐พ DEVICE CACHE FILE ๐พ
Examining all members of the /dev (or /devices) node tree with stat(2) functions can be time consuming. And honestly? The information lsof needs โ device number, inode number, and path โ rarely changes. So why do all that work every time. ๐
Consequently, lsof normally maintains an ASCII text file of cached /dev (or /devices) information (exception: the /proc-based Linux lsof, where it's not needed.) The local system administrator who builds lsof can control the way the device cache file path is formed, selecting from these options:
- Path from the
-Doption; - Path from an environment variable;
- System-wide path;
- Personal path (the default);
- Personal path, modified by an environment variable.
Consult the output of the -h, -D?, or -? help options for the current state of device cache support. The help output lists the default read-mode device cache file path that is in effect for the current invocation of lsof. The -D? option output lists the read-only and write device cache file paths, the names of any applicable environment variables, and the personal device cache path format. Very thorough of her. โจ
Lsof can detect that the current device cache file has been accidentally or maliciously modified by integrity checks, including the computation and verification of a sixteen bit Cyclic Redundancy Check (CRC) sum on the file's contents. When lsof senses something wrong with the file, it issues a warning and attempts to remove the current cache file and create a new copy โ but only to a path that the process can legitimately write. No funny business. ๐ซ
The path from which a lsof process may attempt to read a device cache file may not be the same as the path to which it can legitimately write. So when lsof senses that it needs to update the device cache file, it may choose a different path for writing it from the path from which it read an incorrect or outdated version. Lowkey efficient.
If available, the -Dr option will inhibit the writing of a new device cache file. (It's always available when specified without a path name argument.) ๐
When a new device is added to the system, the device cache file may need to be recreated. Since lsof compares the mtime of the device cache file with the mtime and ctime of the /dev (or /devices) directory, it usually detects that a new device has been added; in that case lsof issues a warning message and attempts to rebuild the device cache file.
Whenever lsof writes a device cache file, it sets its ownership to the real UID of the executing process, and its permission modes to 0600, this restricting its reading and writing to the file's owner. ๐
๐ LSOF PERMISSIONS THAT AFFECT DEVICE CACHE FILE ACCESS ๐
Two permissions of the lsof executable affect its ability to access device cache files. The permissions are set by the local system administrator when lsof is installed.
๐ฅ Permission One: setuid-root
The first and rarer permission is setuid-root. It comes into effect when lsof is executed; its effective UID is then root, while its real (i.e., that of the logged-on user) UID is not. The lsof distribution recommends that versions for these dialects run setuid-root:
HP-UX 11.11 and 11.23Linux
๐ฅ Permission Two: setgid
The second and more common permission is setgid. It comes into effect when the effective group IDentification number (GID) of the lsof process is set to one that can access kernel memory devices โ e.g., kmem'', sys'', or ``system''.
An lsof process that has setgid permission usually surrenders the permission after it has accessed the kernel memory devices. When it does that, lsof can allow more liberal device cache path formations. The lsof distribution recommends that versions for these dialects run setgid and be allowed to surrender setgid permission:
AIX 5.[12] and 5.3-ML1Apple Darwin 7.x Power Macintosh systemsFreeBSD 4.x, 4.1x, 5.x and [6789].x for x86-based systemsFreeBSD 5.x, [6789].x and 1[012].8for Alpha, AMD64 and Sparc64 based systemsHP-UX 11.00NetBSD 1.[456], 2.x and 3.x for Alpha, x86, and SPARC-based systemsOpenBSD 2.[89] and 3.[0-9] for x86-based systemsSCO OpenServer Release 5.0.6 for x86-based systemsSCO|Caldera UnixWare 7.1.4 for x86-based systemsSolaris 2.6, 8, 9 and 10Tru64 UNIX 5.1
Note:lsoffor AIX 5L and above needssetuid-rootpermission if its-Xoption is used.
Finally โ lsof for these dialects does not support a device cache, so the permissions given to the executable don't apply to the device cache file:
Linux
๐
DEVICE CACHE FILE PATH FROM THE -D OPTION
Okay so the -D option gives you limited ways to say where the device cache file should live. Emphasis on limited, bestie โ it's not a free-for-all. Its ? function will report the read-only and write device cache file paths that lsof will use. Like a little vibe check of your paths โจ
When the -D b, r, and u functions are available, you can use them to request that the cache file be:
- built in a specific location โ that's
b[path] - read but not rebuilt โ that's
r[path] - read and rebuilt โ that's
u[path]
But here's the catch ๐ซ the b, r, and u functions are restricted under some conditions. They're restricted when the lsof process is setuid-root. And the path specified with the r function is always read-only, even when it is available. No take-backs.
The b, r, and u functions are also restricted when the lsof process runs setgid and lsof doesn't surrender the setgid permission. (Peep the LSOF PERMISSIONS THAT AFFECT DEVICE CACHE FILE ACCESS section for the list of implementations that normally don't surrender their setgid permission ๐)
A further -D function, i (for ignore), is always available. Periodt.
When available, the b function tells lsof to read device information from the kernel with the stat(2) function and build a device cache file at the indicated path.
When available, the r function tells lsof to read the device cache file, but not update it. When a path argument accompanies -Dr, it names the device cache file path. The r function is always available when it is specified without a path name argument. If lsof is not running setuid-root and surrenders its setgid permission, a path name argument may accompany the r function. Conditional queen ๐
When available, the u function tells lsof to attempt to read and use the device cache file. If it can't read the file, or if it finds the contents of the file incorrect or outdated, it will read information from the kernel, and attempt to write an updated version of the device cache file โ but only to a path it considers legitimate for the lsof process effective and real UIDs. Safety first, always ๐ก๏ธ
๐ธ DEVICE CACHE PATH FROM AN ENVIRONMENT VARIABLE
lsof's second choice for the device cache file is the contents of the LSOFDEVCACHE environment variable. She avoids this choice if the lsof process is setuid-root, or the real UID of the process is root. Not today, root ๐ซ
A further restriction applies to a device cache file path taken from the LSOFDEVCACHE environment variable: lsof will not write a device cache file to the path if the lsof process doesn't surrender its setgid permission. (See the LSOF PERMISSIONS THAT AFFECT DEVICE CACHE FILE ACCESS section for info on implementations that don't surrender their setgid permission.)
The local system administrator can disable the use of the LSOFDEVCACHE environment variable or change its name when building lsof. So consult the output of -D? for the environment variable's name โ it might not be called what you think ๐
๐ฆ SYSTEM-WIDE DEVICE CACHE PATH
The local system administrator may choose to have a system-wide device cache file when building lsof. That file will generally be constructed by a special system administration procedure when the system is booted or when the contents of /dev or /devices changes. If defined, it is lsof's third device cache file path choice.
You can tell that a system-wide device cache file is in effect for your local installation by examining the lsof help option output โ i.e., the output from the -h or -? option. Slay, documented ๐
lsof will never write to the system-wide device cache file path by default. It must be explicitly named with a -D function in a root-owned procedure. Once the file has been written, the procedure must change its permission modes to 0644 (owner-read and owner-write, group-read, and other-read).
Fr fr, that 0644 detail matters โ don't leave your system-wide cache file sitting there with weird modes ๐
๐ PERSONAL DEVICE CACHE PATH (DEFAULT)
The default device cache file path of the lsof distribution is one recorded in the home directory of the real UID that executes lsof. Added to the home directory is a second path component of the form .lsof_hostname. Cute little hidden file, main character energy ๐
This is lsof's fourth device cache file path choice, and is usually the default. If a system-wide device cache file path was defined when lsof was built, this fourth choice will be applied when lsof can't find the system-wide device cache file. This is the only time lsof uses two paths when reading the device cache file.
The hostname part of the second component is the base name of the executing host, as returned by gethostname(2). The base name is defined to be the characters preceding the first . in the gethostname(2) output, or all the gethostname(2) output if it contains no .. Chop the dot, keep the rest โ๏ธ
The device cache file belongs to the user ID and is readable and writable by the user ID alone โ i.e., its modes are 0600. Each distinct real user ID on a given host that executes lsof has a distinct device cache file. The hostname part of the path distinguishes device cache files in an NFS-mounted home directory into which device cache files are written from several different hosts. It's giving organized โจ
The personal device cache file path formed by this method represents a device cache file that lsof will attempt to read, and will attempt to write should it not exist or should its contents be incorrect or outdated.
The -Dr option without a path name argument will inhibit the writing of a new device cache file. Read-only era ๐
The -D? option will list the format specification for constructing the personal device cache file. The conversions used in the format specification are described in the 00DCACHE file of the lsof distribution.
๐ง MODIFIED PERSONAL DEVICE CACHE PATH
If this option is defined by the local system administrator when lsof is built, the LSOFPERSDCPATH environment variable contents may be used to add a component of the personal device cache file path.
The LSOFPERSDCPATH variable contents are inserted in the path at the place marked by the local system administrator with the %p conversion in the HASPERSDC format specification of the dialect's machine.h header file. (It's placed right after the home directory in the default lsof distribution.)
So for example: if LSOFPERSDCPATH contains LSOF, the home directory is /Homes/abe, the host name is lsof.itap.purdue.edu, and the HASPERSDC format is the default (%h/%p.lsof_%L), the modified personal device cache file path is:
/Homes/abe/LSOF/.lsof_vic
The LSOFPERSDCPATH environment variable is ignored when the lsof process is setuid-root or when the real UID of the process is root.
lsof will not write to a modified personal device cache file path if the lsof process doesn't surrender setgid permission. (See the LSOF PERMISSIONS THAT AFFECT DEVICE CACHE FILE ACCESS section for a list of implementations that normally don't surrender their setgid permission.)
If, for example, you want to create a sub-directory of personal device cache file paths by using the LSOFPERSDCPATH environment variable to name it, and lsof doesn't surrender its setgid permission, you will have to allow lsof to create device cache files at the standard personal path and move them to your subdirectory with shell commands. Manual labor, literally ๐ญ
The local system administrator may:
- disable this option when
lsofis built - change the name of the environment variable from
LSOFPERSDCPATHto something else - change the
HASPERSDCformat to include the personal path component in another place - or exclude the personal path component entirely
Consult the output of the -D? option for the environment variable's name and the HASPERSDC format specification ๐ซถ
๐ฅ DIAGNOSTICS
Errors are identified with messages on the standard error file. So watch your stderr, bestie ๐
lsof returns a one (1) if any error was detected, including the failure to locate command names, file names, Internet addresses or files, login names, NFS files, PIDs, PGIDs, or UIDs it was asked to list. If the -V option is specified, lsof will indicate the search items it failed to list. If the -Q option is specified, lsof will ignore any search item failures and only return an error if something unusual and unrecoverable happened. Excuse me, unrecoverable?? ๐
It returns a zero (0) if no errors were detected and if either the -Q option was specified or it was able to list some information about all the specified search arguments. Zero means clean, we love a clean exit ๐
When lsof cannot open access to /dev (or /devices) or one of its subdirectories, or get information on a file in them with stat(2), it issues a warning message and continues. That lsof will issue warning messages about inaccessible files in /dev (or /devices) is indicated in its help output โ requested with the -h or -? options โ with the message:
Inaccessible /dev warnings are enabled.
The warning message may be suppressed with the -w option. It may also have been suppressed by the system administrator when lsof was compiled by the setting of the WARNDEVACCESS definition. In this case, the output from the help options will include the message:
Inaccessible /dev warnings are disabled.
Inaccessible device warning messages usually disappear after lsof has created a working device cache file. Bestie fixed it, no cap โจ
๐ EXAMPLES ๐
okay so if you want a much bigger stash of examples, documented more fully, bestie, go check the 00QUICKSTART file of the lsof distribution. it's giving โdirector's cutโ energy โจ
- to list all open files, use:
lsof
- to list all open Internet, x.25 (HP-UX), and UNIX domain files, use:
lsof -i -U
- to list all open IPv4 network files in use by the process whose PID is 1234, use:
lsof -i 4 -a -p 1234
- if it's okay for PID 1234 to not exist, or for PID 1234 to not have any open IPv4 network files, add
-Q:
lsof -Q -i 4 -a -p 1234
- presuming the UNIX dialect supports IPv6, to list only open IPv6 network files, use:
lsof -i 6
- to list all files using any protocol on ports 513, 514, or 515 of host
wonderland.cc.purdue.edu, use:
lsof -i @wonderland.cc.purdue.edu:513-515
- to list all files using any protocol on any port of
mace.cc.purdue.eduโ and yes,cc.purdue.eduis the default domain โ use:
lsof -i @mace
- to list all open files for login name ``abe'', or user ID 1234, or process 456, or process 123, or process 789, use:
lsof -p 456,123,789 -u 1234,abe
- to list all open files on device
/dev/hd4, use:
lsof /dev/hd4
- to find the process that has
/u/abe/fooopen without worrying if there are none, use:
lsof -Q /u/abe/foo
- to take action only if a process has
/u/abe/fooopen, use:
lsof /u/abe/foo echo "still in use"
- to send a SIGHUP to the processes that have
/u/abe/baropen, use:
kill -HUP `lsof -t /u/abe/bar`
- to find any open file, including an open UNIX domain socket file, with the name
/dev/log, use:
lsof /dev/log
- to find processes with open files on the NFS file system named
/nfs/mount/pointwhose server is inaccessible, presuming your mount table supplies the device number for/nfs/mount/point, use:
lsof -b /nfs/mount/point
- to do the preceding search with warning messages suppressed, use:
lsof -bw /nfs/mount/point
- to ignore the device cache file, use:
lsof -Di
- to obtain PID and command name field output for each process, file descriptor, file device number, and file inode number for each file of each process, use:
lsof -FpcfDi
- to list the files at descriptors 1 and 3 of every process running the lsof command for login ID ``abe'' every 10 seconds, use:
lsof -c lsof -a -d 1 -d 3 -u abe -r10
- to list the current working directory of processes running a command that is exactly four characters long and has an
'o'or'O'in character three, use this regular expression form of the-c coption:
lsof -c /^..o.$/i -a -d cwd
- to find an IP version 4 socket file by its associated numeric dot-form address, use:
lsof -i@128.210.15.17
- to find an IP version 6 socket file (when the UNIX dialect supports IPv6) by its associated numeric colon-form address, use:
lsof -i@[0:1:2:3:4:5:6:7]
- to find an IP version 6 socket file (when the UNIX dialect supports IPv6) by an associated numeric colon-form address that has a run of zeroes in it โ e.g., the loop-back address โ use:
lsof -i@[::1]
- to obtain a repeat mode marker line that contains the current time, use:
lsof -rm====%T====
- to add spaces to the previous marker line, use:
lsof -r "m==== %T ===="
๐ญ BUGS ๐ญ
okay bestie, this is the โheads up, it's not magicโ section, and we keep it real ๐
- Since lsof reads kernel memory in its search for open files, rapid changes in kernel memory may produce unpredictable results. no cap, the kernel is a moving target sometimes.
- When a file has multiple record locks, the lock status character (following the file descriptor) is derived from a test of the first lock structure, not from any combination of the individual record locks that might be described by multiple lock structures.
- Lsof can't search for files with restrictive access permissions by name unless it is installed with root set-UID permission. Otherwise it is limited to searching for files to which its user or its set-GID group (if any) has access permission.
- The display of the destination address of a raw socket (e.g., for ping) depends on the UNIX operating system. Some dialects store the destination address in the raw socket's protocol control block, some do not.
- Lsof can't always represent Solaris device numbers in the same way that
ls(1)does. For example, the major and minor device numbers that thelstat(2)andstat(2)functions report for the directory on which CD-ROM files are mounted (typically/cdrom) are not the same as the ones that it reports for the device on which CD-ROM files are mounted (typically/dev/sr0). (Lsof reports the directory numbers.) - The support for
/procfile systems is available only for BSD and Tru64 UNIX dialects, Linux, and dialects derived from SYSV R4 โ e.g., FreeBSD, NetBSD, OpenBSD, Solaris, UnixWare. - Some
/procfile items โ device number, inode number, and file size โ are unavailable in some dialects. Searching for files in a/procfile system may require that the full path name be specified. - No text (
txt) file descriptors are displayed for Linux processes. All entries for files other than the current working directory, the root directory, and numerical file descriptors are labeledmemdescriptors. - Lsof can't search for Tru64 UNIX named pipes by name, because their kernel implementation of
lstat(2)returns an improper device number for a named pipe. - Lsof can't report fully or correctly on HP-UX 9.01, 10.20, and 11.00 locks because of insufficient access to kernel data or errors in the kernel data. See the lsof FAQ (the FAQ section gives its location) for details.
- The AIX SMT file type is a fabrication. It's made up for file structures whose type (
15) isn't defined in the AIX/usr/include/sys/file.hheader file. One way to create such file structures is to run X clients with theDISPLAYvariable set to ``:0.0''. - The
+|-f[cfn]option is not supported under/proc-based Linux lsof, because it doesn't read kernel structures from kernel memory.
๐ ENVIRONMENT ๐
Lsof may access these environment variables. vibe check those env vars, bestie ๐
LANGโ defines a language locale. Seesetlocale(3)for the names of other variables that can be used in place ofLANGโ e.g.,LC_ALL,LC_TYPE, etc.LSOFDEVCACHEโ defines the path to a device cache file. See the DEVICE CACHE PATH FROM AN ENVIRONMENT VARIABLE section for more information.LSOFPERSDCPATHโ defines the middle component of a modified personal device cache file path. See the MODIFIED PERSONAL DEVICE CACHE PATH section for more information.
๐ฆ FAQ ๐ฆ
Frequently-asked questions and their answers (an FAQ) are available in the 00FAQ file of the lsof distribution.
That latest version of the file is found at:
https://github.com/lsof-org/lsof/blob/master/00FAQ
๐ FILES ๐
/dev/kmemโ kernel virtual memory device/dev/memโ physical memory device/dev/swapโ system paging device.lsof_hostnameโ lsof's device cache file. (The suffix,hostname, is the first component of the host's name returned bygethostname(2).)
๐ AUTHORS ๐
Lsof was written by Victor A.Abell <abe@purdue.edu> of Purdue University. Since version 4.93.0, the lsof-org team at GitHub maintains lsof. Many others have contributed to lsof. They're listed in the 00CREDITS file of the lsof distribution. iconic collaborative energy, honestly ๐ซถ
๐ฅ DISTRIBUTION ๐ฅ
The latest distribution of lsof is available at:
https://github.com/lsof-org/lsof/releases
โญ SEE ALSO โญ
Not all the following manual pages may exist in every UNIX dialect to which lsof has been ported. so like, check your local dialect before you come for me ๐
access(2), awk(1), crash(1), fattach(3C), ff(1), fstat(8), fuser(1), gethostname(2), isprint(3), kill(1), localtime(3), lstat(2), modload(8), mount(8), netstat(1), ofiles(8L), open(2), perl(1), ps(1), readlink(2), setlocale(3), stat(2), strftime(3), time(2), uname(1).
and that's the whole page, bestie ๐ซถ this is source/version Revision-4.99.7 of LSOF(8) โ the footer doesn't list a separate date, so that's the full cute sign-off. slay, you made it to the end ๐
โจ
๐ฆ where this page comes from
- arch rolling: lsof 4.99.7-1 ยท custom
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms