{"id":166007,"date":"2021-01-29T16:00:06","date_gmt":"2021-01-29T13:00:06","guid":{"rendered":"https:\/\/en.buradabiliyorum.com\/bash-process-termination-hacks-cloudsavvy-it\/"},"modified":"2021-01-29T16:00:06","modified_gmt":"2021-01-29T13:00:06","slug":"bash-process-termination-hacks-cloudsavvy-it","status":"publish","type":"post","link":"https:\/\/buradabiliyorum.com\/en\/bash-process-termination-hacks-cloudsavvy-it\/","title":{"rendered":"#Bash Process Termination Hacks \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-6a2eeb95b4598\" 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-6a2eeb95b4598\" 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\/bash-process-termination-hacks-cloudsavvy-it\/#What_Is_a_Bash_Process\" >What Is a Bash Process?<\/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\/bash-process-termination-hacks-cloudsavvy-it\/#Terminating_a_Bash_Process\" >Terminating a Bash Process<\/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\/bash-process-termination-hacks-cloudsavvy-it\/#Avoiding_Errors_Selecting_Owned_Processes_Only\" >Avoiding Errors &amp; Selecting Owned Processes Only<\/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\/bash-process-termination-hacks-cloudsavvy-it\/#Wrapping_Up\" >Wrapping Up<\/a><\/li><\/ul><\/nav><\/div>\n<p><strong>&#8220;#Bash Process Termination Hacks \u2013 CloudSavvy IT&#8221;<\/strong><\/p>\n<div id=\"article-content-area\">\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-4038\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/f1fee0a0a83b16d260ba2e862cb46eec\/p\/uploads\/2017\/07\/add8ac45.png\" alt=\"Bash Shell\" width=\"1400\" height=\"600\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>When developing multi-threaded Bash code, managing server processes, or creating process watchdogs, one of the main challenge is usually to correctly, efficiently and accurately terminate existing Bash processes. This article will show you how.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"What_Is_a_Bash_Process\"><\/span>What Is a <i>Bash Process<\/i>?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>A Bash process is simply an executable which is running. For example, when you start the calculator in your desktop environment, a Bash process is created. Such a bash has two main process identifiers, namely the <strong>PID<\/strong> and the <strong>PPID<\/strong>, the <i>Process Identifier<\/i>, and the <i>Parent Process Identifier<\/i>.<\/p>\n<p>In summary, the <i>PID<\/i> holds a number based unique ID for a given running <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>lication (i.e. process), whereas the <i>PPID<\/i> for any given running application (i.e. process) stores the <i>Parent PID<\/i> of the process which started this new application, hence the term \u2018Parent\u2019.<\/p>\n<p>You can also im<a href=\"https:\/\/buradabiliyorum.com\/en\/category\/social-mediaa\/\" data-internallinksmanager029f6b8e52c=\"1\" title=\"Social Media\" target=\"_blank\" rel=\"noopener\">media<\/a>tely see how this forms a tree-like structure, interlinking all processes up to the root\/first process which has a <i>PPID<\/i> of 0.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9291\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/7ab910d7937848d0481ae057d60e10bb\/p\/uploads\/2021\/01\/15fa4d32.png\" alt=\"Root processes on Linux \" width=\"634\" height=\"203\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>For a related article which provides additional insights and a practical example of <i>PID<\/i> and <i>PPID<\/i>, you may want to review our Exporting Variables in Bash: the Why and How article.<\/p>\n<p>Bash process management seems easy at first glance (simply run <code>ps -ef<\/code> at your terminal command line to see all processes running on your system, prefixed by their <i>PID<\/i> and <i>PPID<\/i> identifiers.<\/p>\n<p>Even terminating a process seems easy, but soon caveats and gotchas start kicking in when you handle more complex process management systems.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Terminating_a_Bash_Process\"><\/span>Terminating a Bash Process<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Let\u2019s start simple by starting the <code>gnome-calculator<\/code> at the command line and subsequently terminating the process.<\/p>\n<pre>gnome-calculator &amp;&#13;\nps -ef | grep gnome-calculator&#13;\nkill -9 $RELEVANT_PID&#13;\n&#13;\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9307\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/9fc684cbb4e75ca84baf016a67a85c54\/p\/uploads\/2021\/01\/de3c0be6-2.png\" alt=\"A simple process kill in Linux\" width=\"722\" height=\"152\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/pre>\n<p>We started <code>gnome-calculator<\/code> in background mode (by using <code>&amp;<\/code> at the end of the command), so that we may have our terminal prompt back immediately without having to start another terminal session.<\/p>\n<p>Next, we used <code>ps -ef<\/code> in combination with a pipe (<code>|<\/code>) and the <code>grep<\/code> command to locate the process ID (<i>PID<\/i>) of our calculator. Next, we terminated it with a signal 9 <code>kill<\/code> command. Replace <code>$RELEVANT_PID<\/code> in the code with the PID reported by <code>ps<\/code> if you try this code.<\/p>\n<p>Note that the background process is immediately terminated by the <code>kill -9<\/code> instruction. However, the Bash command prompt returns so quickly that it is back even before the process scheduler can report the background process was terminated.<\/p>\n<p>And, it will only do so when that notification is inline with existing work, i.e. it is more pull-based then push-based. When we hit enter, the system checks and notifies us that the first background process has now ended, or rather was terminated\/killed; <code>[1]+ Killed gnome-calculator<\/code>.<\/p>\n<p>Returning to our <code>kill command<\/code>, a signal 9 <code>kill<\/code> is one of the most destructive kills there is. It basically terminates the program on the spot without being nice about it. You can review the \u2018Signal numbering for standard signals\u2019 section accessible from the <code>man signal.7<\/code> command executed at your terminal command prompt for a list of all available signals and their matching numbers.<\/p>\n<p>For the purposes of this article, we will use <i>signal 9<\/i> to always immediately and effectively terminate a process. However, even when using a <i>signal 9<\/i> kill\/process termination, sometimes a process may linger around in a <i>defunct<\/i> state.<\/p>\n<p>It does not often happen in <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/general\/\" data-internallinksmanager029f6b8e52c=\"3\" title=\"General\" target=\"_blank\" rel=\"noopener\">general<\/a> DevOps work, and if it does it usually means there were some serious issues in either the code of the program (the process being ran) to start with, or with the system hardware or operating system.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Avoiding_Errors_Selecting_Owned_Processes_Only\"><\/span>Avoiding Errors &amp; Selecting Owned Processes Only<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Starting again with the process above, is there a way to automate the <i>PID<\/i> selection so we do not need to type in manually, and so we can use it from within a script? There sure is;<\/p>\n<pre>gnome-calculator &amp;&#13;\nps -ef | grep 'gnome-calculator' | grep -v 'grep' | awk '{print $2}'&#13;\nps -ef | grep 'gnome-calculator' | grep -v 'grep' | awk '{print $2}' | xargs kill -9&#13;\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9293\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/6bfa43bd5d203e3dff771844cdfd50fd\/p\/uploads\/2021\/01\/96b89409.png\" alt=\"More well defined process termination in Linux\" width=\"714\" height=\"135\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>Here we again started our <code>gnome-calculator<\/code> in background mode, and again used <code>ps<\/code> and <code>grep<\/code> to find our process. That is where the similarity ends. In the next instruction within the Bash set of pipes (passing information from the previous command through to the next one using a pipe symbol: <code>|<\/code>) we exclude the <code>grep<\/code> process itself (also listed as part of the <code>ps<\/code> output as it is running during our command sequence and is thus self-picked up by the <code>grep<\/code>), by using the <code>-v<\/code> option to <code>grep<\/code> and excluding the word <code>'grep'<\/code>.<\/p>\n<p>Finally, we print the <i>PID<\/i> (process ID) of any discovered processes by using <code>awk<\/code> and printing the second (<code>$2<\/code>) column of the output only. We see that only a single <i>PID<\/i> is returned, which matches the fact that we have only a single <code>gnome-calculator<\/code> started.<\/p>\n<p>Our final command adds an <code>xargs<\/code> command with a <code>kill -9<\/code> instruction to terminate our process(es). xargs works similar to a pipe in itself, but it is better able to handle various input information and pass it on correctly, allowing certain programs like <code>kill<\/code> (which cannot natively understand when plain <i>PID<\/i>\u2018s are being sent to it) to accept direct input, or rather options \u2013 like the process ID\u2019s being transmitted here. Note that xargs is prefixed by a pipe itself.<\/p>\n<p>Our inclusion of a <code>grep -v 'grep'<\/code> avoids not only the error of the eventual <code>kill<\/code> command not being able to find the <i>PID<\/i> associated with the original <code>grep<\/code> command (as it has since terminated, having fulfilled it\u2019s duty of grepping for the <code>'gnome-calculator'<\/code> text), it secondly also prevents the risk of terminating another, newer, command\/process which may have been started since the original <code>grep<\/code> terminated, with the same process ID! Though the possibility of this occurring is small, it is possible.<\/p>\n<p>Working these things into our command looks better, but it\u2019s not perfect yet. What is this is a server with 10 users and all 10 have started a calculator? Assuming we have sudo like privileges, do we really want to terminate the calculator processes of the other users? Likely not. So, we can go one step further and define our command as follows:<\/p>\n<pre>gnome-calculator &amp;&#13;\nps -ef | grep 'gnome-calculator' | grep -v 'grep' | grep \"$(whoami)\" | awk '{print $2}'&#13;\nps -ef | grep 'gnome-calculator' | grep -v 'grep' | grep \"$(whoami)\" | awk '{print $2}' | xargs kill -9&#13;\n&#13;\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9294\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/4484b0345f7d6f072e4fe343fc47cc42\/p\/uploads\/2021\/01\/03282d7f.png\" alt=\"Excluding owned processes from a process termination command\" width=\"904\" height=\"141\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/pre>\n<p>In this example we inserted a small additional command, namely <code>grep \"$(whoami)\"<\/code>, which executed a subshell (<code>$(...)<\/code>) and then executes <code>whoami<\/code> within that subshell. The <code>whoami<\/code> command will return to the terminal the current logged in users. Bingo! We now terminate only our own owned processes.<\/p>\n<p>Perfect? No, regrettably errors are still possible even with such a detailed tuned command line. For example, if the process list contains locale or odd characters, our <code>grep<\/code> may potentially still fail. Perhaps the most safe version would be something alike to:<\/p>\n<pre>gnome-calculator &amp;&#13;\nps -ef | grep -Ei --binary-files=text \"^$(whoami) [0-9 ]+:.*gnome-calculator$\" | grep --binary-files=text -v 'grep' | awk '{print $2}' | grep --binary-files=text  -o '[0-9]+' | xargs -I{} kill -9 \"{}\"&#13;\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9295\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/9ca52e97580b84fb38c63623710d92de\/p\/uploads\/2021\/01\/f7d97bb2.png\" alt=\"A safer version or a multi-process termination command\" width=\"657\" height=\"134\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>In this example, we defined our <code>grep<\/code> command a lot more restrictive with a regular expression: start (indicated by <code>^<\/code>) with the username (using <code>whoami<\/code> in a subshell), followed by a mandatory space, followed by only the characters <code>0-9<\/code> and space, at least one or more (as indicated by <code>+<\/code>), followed by a mandatory colon (part of the time), followed by any character up to our program name, which must fill up to the end of the line (as indicated by <code>$<\/code>). The <code>grep<\/code> uses extended regular expressions (<code>-E<\/code>), and is case insensitive (<code>-i<\/code> option, or simply <code>i<\/code> when added to the existing <code>-E<\/code> option)<\/p>\n<p>We also protected our grep for the odd possibility of locale or odd characters by using <code>--binary-files=text<\/code>, and we wrote our xargs in a more secure manner by indicating a replacement string and quoting the replacement string.<\/p>\n<p>Finally, we inserted an additional <code>grep -o<\/code> with a regular expression that searches for the numbers <code>0-9<\/code> only. Thus, even if some program tried to trick this process killing command line, it would be harder to do so.<\/p>\n<p>As an interesting alternative to defining a parsing command line, you may also want to have a look at the <code>killall<\/code> command:<\/p>\n<pre>gnome-calculator &amp;&#13;\nkillall 'gnome-calculator'&#13;\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9296\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/d5181541614824b3d8f4b86fa8bd1a40\/p\/uploads\/2021\/01\/f1f8b8c4.png\" alt=\"Example of a killall command excution\" width=\"450\" height=\"102\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>For more information on this command, you can access the manual using <code>man killall<\/code>. The <code>killall<\/code> command also allows you to set options like <code>--user<\/code> to only kill processes the specified user owns etc.<\/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>Handling processes in various ways allows us to write process watchdog scripts, automate process handling, better develop multi-threaded bash code, manage processes better and more. <strong>Enjoy your new found Bash skills!<\/strong>\n<\/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\/9290\/bash-process-termination-hacks\/\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;#Bash Process Termination Hacks \u2013 CloudSavvy IT&#8221; When developing multi-threaded Bash code, managing server processes, or creating process watchdogs, one of the main challenge is usually to correctly, efficiently and accurately terminate existing Bash processes. This article will show you how. What Is a Bash Process? A Bash process is simply an executable which is&#8230;<\/p>\n","protected":false},"author":1,"featured_media":166008,"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-166007","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\/166007","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=166007"}],"version-history":[{"count":0,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/166007\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media\/166008"}],"wp:attachment":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media?parent=166007"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/categories?post=166007"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/tags?post=166007"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}