{"id":322833,"date":"2021-08-12T14:00:11","date_gmt":"2021-08-12T11:00:11","guid":{"rendered":"https:\/\/en.buradabiliyorum.com\/how-to-use-lsof-in-linux-with-a-practical-example-cloudsavvy-it\/"},"modified":"2021-08-12T14:00:11","modified_gmt":"2021-08-12T11:00:11","slug":"how-to-use-lsof-in-linux-with-a-practical-example-cloudsavvy-it","status":"publish","type":"post","link":"https:\/\/buradabiliyorum.com\/en\/how-to-use-lsof-in-linux-with-a-practical-example-cloudsavvy-it\/","title":{"rendered":"#How to Use lsof in Linux (With a Practical Example) \u2013 CloudSavvy IT"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_84 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a25546014c48\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #dd3333;color:#dd3333\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #dd3333;color:#dd3333\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a25546014c48\" checked aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-lsof-in-linux-with-a-practical-example-cloudsavvy-it\/#What_Is_lsof\" >What Is lsof?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-lsof-in-linux-with-a-practical-example-cloudsavvy-it\/#Example_Basic_lsof_Output\" >Example: Basic lsof Output<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-lsof-in-linux-with-a-practical-example-cloudsavvy-it\/#Example_Using_lsof_with_kill\" >Example: Using lsof with kill<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/buradabiliyorum.com\/en\/how-to-use-lsof-in-linux-with-a-practical-example-cloudsavvy-it\/#Wrapping_up\" >Wrapping up<\/a><\/li><\/ul><\/nav><\/div>\n<p><strong>&#8220;#How to Use lsof in Linux (With a Practical Example) \u2013 CloudSavvy IT&#8221;<\/strong><\/p>\n<div id=\"article-content-area\">\n<img loading=\"lazy\" decoding=\"async\" class=\"type:primaryImage alignnone size-full wp-image-4038\" srcset=\"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2017\/07\/add8ac45.png?width=398&amp;trim=1,1&amp;bg-color=000&amp;pad=1,1 400w, https:\/\/www.cloudsavvyit.com\/p\/uploads\/2017\/07\/add8ac45.png?width=1198&amp;trim=1,1&amp;bg-color=000&amp;pad=1,1 1200w\" sizes=\"auto, 400w, 1200w\" src=\"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2017\/07\/add8ac45.png?width=1198&amp;trim=1,1&amp;bg-color=000&amp;pad=1,1\" alt=\"How to Use lsof in Linux with a Practical Example\" width=\"1400\" height=\"600\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>Ever wondered how to discover what files are currently open and in use on your system? The Linux lsof command lists open files and provides plenty of extra information. Learn how to use lsof with these practical examples.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"What_Is_lsof\"><\/span>What Is <i>lsof<\/i>?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Available natively within any Linux operating system, the <code>lsof<\/code> command provides a list of open files. However, the output can be a bit cryptic and long, especially when using many <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/download-scripts-themes-apps\/\" data-internallinksmanager029f6b8e52c=\"9\" title=\"Download Scripts &amp; Themes &amp; Apps\" target=\"_blank\" rel=\"noopener\">app<\/a>lications on a given system. Let\u2019s have a look at basic <code>lsof<\/code> output. We will be running <code>lsof<\/code> as root.<\/p>\n<p>To login as root, you can open a terminal window and type a command like <code>sudo su<\/code> or <code>su<\/code> to receive a root authentication prompt. Alternatively, you can execute <code>sudo lsof<\/code>. Note that while you can run <code>lsof<\/code> as a normal non-root user also, you may find that the output is incomplete.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Example_Basic_lsof_Output\"><\/span>Example: Basic <i>lsof<\/i> Output<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<pre>sudo su&#13;\nlsof | head -n10&#13;\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-13146\" src=\"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/08\/4a47a0db.png?trim=1,1&amp;bg-color=000&amp;pad=1,1\" alt=\"Start of lsof output and lsof column names in a Bash terminal\" width=\"1247\" height=\"202\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>Here we started the <i>lsof<\/i> tool using the <code>lsof<\/code> command, and captured the first ten lines of the output using a pipe (<code>|<\/code>) to sent the information output by <code>lsof<\/code> to a secondary <code>head -n10<\/code> command which captures only the top (head) ten lines.<\/p>\n<p>The <code>lsof<\/code> command lists various columns. First up we see the <i>COMMAND<\/i> column which lists the binary which is holding the open file\/open file lock. Next we see the process ID column <i>PID<\/i> which is extremely handy when it comes to debugging various application issues, including incorrectly held file locks. In the next section we will look at an example of how we can use <code>lsof<\/code> in combination with <code>kill<\/code> to (destructively) terminate applications which hold incorrect file locks.<\/p>\n<p>If supported on your operating system, the <i>TID<\/i> column can help to realize whether a given line is a process or a task. If the output is blank, as can be seen in our example (which is running on Linux Mint, an operating system that supports the <i>TID<\/i> column output), the given line\/command is a process, a non-task. If you, for example, start a calculator app in your operating system, i.e., a task, this column will be populated by a task\/thread identification number.<\/p>\n<p>The <i>TASKCMD<\/i> column holds the task command name. Again it is only visible if the given line is a task and not a process. This is regularly the same as the command\/process shown in the first <i>COMMAND<\/i> column, though, for example, Linux allows a task to change its command name, so it could contain additional information about the task. The <i>USER<\/i> column lists the user who started the process\/task.<\/p>\n<p>Next up we have an important column <i>FD<\/i> (File Descriptor) which can list the <i>File Descriptor Number<\/i> or a specific text string indicating what type of file descriptor this is. For example, if you see <code>cwd<\/code> in this column, it stands for <i>current working directory<\/i> and it indicates that the given process or task is holding an open lock on the current working directory and that working directory is listed under the <i>NAME<\/i> column.<\/p>\n<p>For a full list of all possible <code>FD<\/code> strings, type <code>man lsof<\/code> at your command prompt followed by typing <code>\/ FD<\/code> (with 3 spaces after slash and before FD) once inside the manual, and then pressing <i>ENTER<\/i> to search for the FD section.<\/p>\n<p>When it comes to regular files, you may think about the <i>FD<\/i> column like a counter, or a unique ID counter, starting at 0 and increasing to the total number of regular open files on the system, with the maximum number of open files being defined by the <i>ulimit -n<\/i> setting, etc.<\/p>\n<p>When looking at regular files, the <i>FD<\/i> column will for example show <code>102u<\/code> or <code>13w<\/code>. These two examples respectively represent <i>the 102th open file on the system, in mixed read\/write access mode, as indicated by the <code>u<\/code> indicator\/label<\/i> and <i>the 13th open file on the system, in write access mode only<\/i>.<\/p>\n<p>The <i>TYPE<\/i> column is quite self-explanatory; it indicates whether a regular file or a directory open lock is being held. There are various other labels that could be displayed here, and a search for <code>\/ TYPE<\/code> in <code>man lsof<\/code> (as explained above) will provide a full list.<\/p>\n<p>The <i>DEVICE<\/i> column <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/general\/\" data-internallinksmanager029f6b8e52c=\"3\" title=\"General\" target=\"_blank\" rel=\"noopener\">general<\/a>ly lists the device numbers, separated by commas, for most types of files. The <code>SIZE\/OFF<\/code> column is the size of the file, or the file offset in bytes, and the <i>NODE<\/i> column commonly displays the file node or NFS file inode number of local files. It can also list for example <i>TCP<\/i> or <i>UDP<\/i> when the given lock is an open Internet connection.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Example_Using_lsof_with_kill\"><\/span>Example: Using <i>lsof<\/i> with <i>kill<\/i><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Using <code>lsof<\/code> in combination with <code>grep<\/code>, <code>awk<\/code> and <code>kill<\/code> one can search a given system for a specific file and subsequently terminating the process (using the <i>PID<\/i>, or Process Identifier, described earlier).<\/p>\n<p>Note that this should only be done in situations where it makes sense to do so. For example, you may have a multi-threaded Bash script that starts many different subshells where each one holds on to a given file, and you expect that one of the subprocesses is hanging. You know the open filename of the hanging process but do not know what the <i>PID<\/i> for that process\/task is.<\/p>\n<p>In such a situation, we can execute the following commands:<\/p>\n<pre>sudo su&#13;\nlsof | grep 'some_file_descriptor' | awk '{print $2}' | xargs -I{} kill -9 {}&#13;\n<\/pre>\n<p>Let\u2019s put this into a practical example. Assume we have created the following script <code>test.sh<\/code> in <code>\/tmp<\/code>:<\/p>\n<pre>rm -Rf workspace&#13;\nmkdir workspace&#13;\ncd workspace&#13;\nsleep 36000&#13;\n<\/pre>\n<p>This script, when executed, will create a directory named <code>workspace<\/code>, change directories into it with <code>cd<\/code> and then <code>sleep<\/code> for 10 hours. Whilst at first glance this would not seem to open any files, remember the <code>cwd<\/code> discussed earlier; the script has a current working directory in use namely <code>\/tmp\/workspace<\/code>!<\/p>\n<p>Let\u2019s see how this works out practically. First, we define (using your favorite text editor like <code>vi<\/code>), and then start the script in one terminal session:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-13147 size-full\" src=\"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/08\/fb5c81ed.png?trim=1,1&amp;bg-color=000&amp;pad=1,1\" alt=\"Running a test.sh script which will hold open directories as later listed by lsof\" width=\"632\" height=\"201\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>Next we jump into a secondary\/new terminal session and execute <code>lsof<\/code>, looking for the script\u2019s work directory namely <code>workspace<\/code>:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-13148\" src=\"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/08\/10fb15c7.png?trim=1,1&amp;bg-color=000&amp;pad=1,1\" alt=\"lsof with a grep for matching text is a great way to search the verbose lsof output\" width=\"993\" height=\"71\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>As we can see, <code>lsof<\/code> is able to find not only our test script <code>test.sh<\/code> which is holding a <code>cwd<\/code> lock on <code>\/tmp\/workspace<\/code>, but we also see that <code>sleep<\/code>, started from within the script, is holding a <code>cwd<\/code> open file (or better directory) descriptor on the same directory.<\/p>\n<p>We can also see both the <i>PID<\/i> for the <code>test.sh<\/code> script as well as for the <code>sleep<\/code> command. Let\u2019s assume for a second that our <code>test.sh<\/code> script was hanging, and we wanted to completely terminate it destructively, i.e. with <code>kill -9<\/code> which is the most destructive way to terminate a process without any level of graceful shutdown, and this based on any open files (or in our case open directories) the script was holding. We issue the following command from the secondary terminal:<\/p>\n<pre>lsof | grep \"workspace\" | awk '{print $2}' | xargs -I{} kill -9 {}&#13;\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-13149\" src=\"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/08\/09dd8c26.png?trim=1,1&amp;bg-color=000&amp;pad=1,1\" alt=\"Kill a process using kill -9 based on a lsof search using grep\" width=\"640\" height=\"38\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>This command will take the previous output and parse it further. The <code>awk '{print $2}'<\/code> basically samples out the secondary column (the process ID\u2019s) and the <code>xargs<\/code> command will pass this second column to <code>kill -9<\/code> (the <code>{}<\/code> in the command will be replaced by whatever input <code>xargs<\/code> receives).<\/p>\n<p>We could also anticipate that <code>lsof<\/code> has a header line that contains <code>PID<\/code> and this text will be passed onto kill as well. Whilst it will not create an issue, a better overall command would have read <code>lsof | grep \"workspace\" | grep -v \"PID\" | awk '{print $2}' | xargs -I{} kill -9 {}<\/code>, or some other way of filtering the first line altogether.<\/p>\n<p>The result in our first\/primary terminal session is that our script is instantly killed:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-13150\" src=\"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/08\/8266e4bf.png?trim=1,1&amp;bg-color=000&amp;pad=1,1\" alt=\"test.sh script killed output as a result of the kill executed in the other terminal\" width=\"180\" height=\"61\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>If you would like to learn more about <i>xargs<\/i>, you can read about\u00a0Using xargs in Combination With bash -c to Create Complex Commands. For Bash multi-threaded programming, see How to Use Multi-Threaded Processing in Bash Scripts.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Wrapping_up\"><\/span>Wrapping up<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>In this article we explored using <code>lsof<\/code>, the list open files command, and what information each of the columns in its default output represents. We also looked at a practical use case where we used <code>lsof<\/code> in combination with <code>grep<\/code>, <code>awk<\/code> and <code>kill<\/code> to find a particular file (or in our case a directory) being held open by a script and subsequently terminate that script thereby closing the open directory.<\/p>\n<p>If you enjoyed reading this article, have a look at our Asserts, Errors, and Crashes: What\u2019s the Difference? article.\n<\/p><\/div>\n<blockquote><p><strong><span style=\"color: #ff6600;\">If you liked the article, do not forget to share it with your friends. Follow us on\u00a0<span style=\"color: #ff0000;\"><a style=\"color: #ff0000;\" href=\"https:\/\/news.google.com\/publications\/CAAqBwgKMLG0nwswvr63Aw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">Google News<\/a><\/span>\u00a0too, click on the star and choose us from your favorites.<\/span><\/strong><\/p><\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\">For forums sites go to <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/forum.buradabiliyorum.com\/\" target=\"_blank\" rel=\"noopener\">Forum.BuradaBiliyorum.Com<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\"><strong>If you want to read more like this article, you can visit our <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/en.buradabiliyorum.com\/technology\/\" target=\"_blank\" rel=\"noopener\">Technology category.<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<p><span style=\"color: black;\"><a style=\"color: #ff9900;\" href=\"https:\/\/www.cloudsavvyit.com\/13145\/how-to-use-lsof-in-linux-with-a-practical-example\/\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;#How to Use lsof in Linux (With a Practical Example) \u2013 CloudSavvy IT&#8221; Ever wondered how to discover what files are currently open and in use on your system? The Linux lsof command lists open files and provides plenty of extra information. Learn how to use lsof with these practical examples. What Is lsof? Available&#8230;<\/p>\n","protected":false},"author":1,"featured_media":322834,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"fifu_image_url":"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2017\/07\/add8ac45.png","fifu_image_alt":"","footnotes":""},"categories":[18],"tags":[],"class_list":["post-322833","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/322833","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/comments?post=322833"}],"version-history":[{"count":0,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/322833\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media\/322834"}],"wp:attachment":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media?parent=322833"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/categories?post=322833"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/tags?post=322833"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}